Referrerless redirect in JavaScript

In the world of Google Analytics referrers are important as they tell where did the visit came from. Normally you don’t really want to hide it, but many sites do that because of how outgoing links affect your position on Google index. The typical way to achieve this is through a redirect script that is placed on the server. Then you redirect by calling the script like this*:

Such script would generate html that would look more or less like this:

<meta http-equiv="refresh" content="1; url=">
Redirecting to <a href=""></a>

The thing is, most browsers will lose referrer when refresh is used. If one redirected using a http header, the referrer would be retained. Here is an example of such redirect in php:

$url = $_GET['url'];

// The line below might or might not be required.
// It depending on whether PHP already decoded query parameters for you.
$url = urldecode($url);

// Handling other protocols might be required
if (strpos($url, 'http://') === false)
    $url = 'http://'.$url;

header("HTTP/1.1 301 Moved Permanently");
header("Connection: close");

I guess this is enough introduction, so let’s go to the core of the problem.

Let’s say you write a userscript and for whatever reason you don’t want the referrer to be passed when you redirect (like you don’t want to make the owners of the site, to which you want to redirect to, wonder how come they have users coming from their competitor’s site). The standard way to redirect using JavaScript is through window.location.href, for example:

window.location.href = "";

Turns out that if you use this method the referrer is retained. So how to get rid of the referrer while redirecting using JavaScript?

Of course you can place a redirect script on some external server or rely on an existing service that offers such redirects, but either solution relies on resources that are separate from the script and might break at any time.

Thankfully you can make a referrerless redirect in JavaScript. The trick is to use Data URI. Basically instead of putting a new url in window.location.href you put a redirect page directly there (yes, you put html there). The code might look like this:

window.location.href =
	'data:text/html;charset=utf-8,' +
	    '<meta http-equiv="refresh" content="1; url=">' +
	    'Redirecting to <a href=""></a>'

With this your redirect is referrer free. Maybe later I’ll share my userscript for checking referrer and\or turn the above code into a jquery plugin.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s