Programmatic Navigation

From GreaseSpot Wiki
Jump to: navigation, search

It's possible in Javascript to navigate to a new page with a simple expression:

document.location = '';
document.location.href = '';

This, however, is treating the document.location object as if it were a string. In some cases (simple reading and assignment) this works, but it can fail if, i.e., calling String object methods (like .indexOf() or .substr()). This is slightly remedied by looking at the .href property, which really is a string representing the location, and not an object with other properties.

However, it also relies on the non-standardized behavior that assigning a new value changes the document location. This can be written more clearly as:


The former example operates as a normal navigation. The latter operates like a redirect, replacing the old page with the new page in the browser history. Thus, a press of the back button skips the previous page. Sometimes, this is just the behavior you want!