Dive Into Greasemonkey

Teaching an old web new tricks

5.1. Case study: GMail Secure

Forcing a site to use a secure connection

GMail Secure forces GMail to use a secure connection, by redirecting http://gmail.google.com/ to https://gmail.google.com/.

Google offers GMail, their webmail service, through an unsecured connection (an http:// address) or a secure connection (an https:// address). I could try to remember to always use the secure connection when I'm checking my email on a public network (such as an Internet cafe), but why bother when my computer can do remember it for me? I wrote a user script that detects when I'm attempting to use GMail over an unsecure connection and redirects me to the secure site instead.

Example: Redirect GMail to an equivalent https:// address

// ==UserScript==
// @name          GMailSecure
// @namespace     http://diveintogreasemonkey.org/download/
// @description   force GMail to use secure connection
// @include       http://gmail.google.com/*
// ==/UserScript==

window.location.href = window.location.href.replace(/^http:/, 'https:');

This user script is very simple. Most of the “work” is accomplished by the @include line:

// @include       http://gmail.google.com/*

This user script only runs if the @include matches, so if the script is running, I already know I'm in the wrong place (in the sense that I'm using GMail over an insecure connection). Given that, accomplishing my goal is a single line of code, to redirect the current page to the same URL, but with an https:// prefix instead of http://.

window.location.href = window.location.href.replace(/^http:/, 'https:');
← Case Studies
Case study: Bloglines Autoload →