views:

76

answers:

2

Is there any way to get the previous url in javascript? Something like this:

alert("previous url is: " + window.history.previous.href);

Is there something like that? Or should I just store it in a cookie? I only need to know so I can do transitions from the previous url to the current url without anchors and all that.

+4  A: 
document.referrer

in many cases will get you the URL of the last page the user visited, if they got to the current page by clicking a link (versus typing directly into the address bar, or I believe in some cases, by submitting a form?). More here.

window.history allows navigation, but not access to URLs in the session for security and privacy reasons. If more detailed URL history was available, then every site you visit could see all the other sites you'd been to.

If you're dealing with state moving around your own site, then it's possibly less fragile and certainly more useful to use one of the normal session management techniques: cookie data, URL params, or server side session info.

quixoto
There's also document.referrer, if you arrived at the current page via a link (but not, for example, by bookmark or typing in the address bar).
Hellion
It's not always working. Ie. iframes.
Tomasz Wysocki
Thanks, added note re: document.referrer.
quixoto
i ended up storing the previous url in cookies for the site, `document.referrer` doesn't always work. `$.cookie("previousUrl", window.location.href, {path:"/"});`.
viatropos
+4  A: 

Hey, you can always use

document.referrer

.

This is a standard one, It will give the url from which you have visited.

kapser