Donny Gunawan
Donny Gunawan

Reputation: 363

Check if last window History is from a certain URL

Whether possible to check if last browser history is from mysite.com, then goBack() else goHome() ?

Let's say

Upvotes: 3

Views: 4055

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074969

You can use document.referrer to get the URL of the page that linked to the current page. Note that this is easily spoofed.

That will only work if the user followed a link from the previous page to get to the current page. If they used a bookmark, or typed in a URL, etc., referrer will be blank and there is no way for you to get the information about what was in the window previously. (In particular: There's nothing in the history object that will tell you.) That's simply information that is not available in the browser.

Upvotes: 3

Armen Vardanyan
Armen Vardanyan

Reputation: 3315

You may try using document.referrer and the history API for a solution, but note this is not going to work always:

if (document.referrer === 'my.domain.com') {
   history.back(); // act as if user clicked the browser back button
} 
else {
   window.location.href = 'http://my.domain.com/home';
}

Won't work on IE and the document.referrer is not always accurate, see single page applications

Upvotes: 0

Related Questions