Get the previous URL with javascript

Asked

Viewed 3,619 times

8

How do I get the previous URL of the current javascript page?

  • 2

    To get the previous url, just use document.referrer. To go back to the previous page, just use history.back()

1 answer

9

document.referrer

According to the MDN in my own translation;

Returns the URI of the page that made the link. Returns an empty string if the user navigated to the page directly (not through a link, for example through a Bookmark). Since this property returns a string it does not give you DOM access to the referred page

This property is in the specification of the DOM so it’s supposed to be cross browser, however you can test if the browser implements it this way;

if( typeof document['referrer'] !== 'undefined' ) { 
    //Seu browser suporta document.referrer
}

Observing: Some versions of IE do not always define this property; see this thread (in English)

Observation 2: Maybe you might be interested in worrying about anti-XSS security while using document.referrer, is an issue already raised by others (also in English).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.