distinguishing between pages using JavaScript

88 views Asked by At

I'm curious as to how I'd get JavaScript to distinguish between two near identical pages which (as far as I can tell) have the same div's. An example of a page like this would be Google Home Page vs. Google Search Results. Is there anyway I can correctly identify which is which?

2

There are 2 answers

7
T.J. Crowder On

In that specific example, window.title will distinguish them. window.title isn't supported by Chrome, but document.title is. It works in Chrome, Firefox, and Opera on both Linux and Windows; Safari on Windows; IE6, IE7, and IE8 on Windows; and probably others as well.

More generally, window.location gives you the URL of the page, which is good for telling what page you're on; more on MDC. It's supported on every major browser I've ever seen, including the list above.

2
Harmen On

Since HTML5, you can edit the browser history. For example, you can change the current URL with window.history.pushState():

// pushState(state object, title, URL)
window.history.pushState({foo: "bar"}, "page 2", "bar.html");

This makes the user remain on exactly the same page, but changes the URL. This is happening on the current version of Google's homepage too, so the page is still the same.

You can retrieve the URL with window.location.