Google-chrome – How does the browser know I’ve visited a page if the URL is redirecting

browsergoogle-chromegoogle-searchhistorysafari

How do Chrome, Safari, Firefox or other browsers know you've visited the destination URL of a redirecting link?

I've always found it interesting that the browsers know the URL a redirecting URL lands on and apply the visited styling to the link.

To understand what I'm asking:

  • Type a random keyword into Google.
  • Find a blue link in the search result. Do not click on it.
  • Copy the destination URL (usually written in green beneath the link).
  • Open a new window/tab and paste the destination URL in the address bar and hit Enter.
  • Go back to the Google search results and immediately the link becomes visited and turns purple.

However, the link is to some google.com/url... page. Is there something Google puts in their markup to tell the browser what URL to affiliate the link's history with or something? Do browsers just read the Google search results a certain way?

Best Answer

If you pay attention to the status bar while hovering the link, you'll see that it initially points to the "clean" URL.

Only when you click on the link (with any of the three mouse buttons), a JavaScript event gets triggered that changes the link's destination to Google's URL redirection.

To verify my claim, just right-click any of the purple links and close the context menu. Unless you already visited the site from within Google's search results, you'll see that it changes colors.1

I don't know exactly how Google injects the redirection URL2, but the general idea is this:

// define a function `f' that changes a link's clean URL to a redirection URL
var f = function () {
    // prepend `http://www.google.com/url?rct=j&url=' to the link's target
    this.href = 'http://www.google.com/url?rct=j&url=' + escape(this.href);
    // don't invoke this function anymore when clicking the link
    this.removeEventListener('click', f);
    // don't invoke this function anymore when right-clicking the link
    this.removeEventListener('contextmenu', f);
}

// save all <a> tags in an array `a'
var a = document.getElementsByTagName('a');

// for each <a> tag in the array `a'
for (var i = 0; i < a.length; i++) {
    // execute function `f' when clicking the link
    a[i].addEventListener('click', f);
    // execute function `f' when right-clicking the link
    a[i].addEventListener('contextmenu', f);
}

You can try this jsFiddle to see how it works.


1 Tested on Chromium 25 (Ubuntu 12.10) and Chrome 26 (Windows 7)

2 Minimized JavaScript is a bit difficult to read.

Related Question