Minirock
Minirock

Reputation: 666

Detect navigation history inside/outside website

I would like to know where the user come from in each one of my pages in order to provide a back button functionnality like the one by default in browsers.

To do such a thing, right now I'm using document.referer , if it's empty, I'm doing a custom redirection with location.href and otherwise I just call history.back

It works, but there is still a little issue with this process.

If the user comes to the page using a link from outside the website different from a bookmark (like a google research for example). Then I would like to be able to handle this to avoid using history.back to avoid falling again on google and doing a custom redirection too in this specific case.

So I was asking if something more tuchy than document.referer where existing to detect if the last url was inside or outside the website.

Upvotes: 1

Views: 901

Answers (1)

Obed Parlapiano
Obed Parlapiano

Reputation: 3682

There's no in-built functionality that lets you do this, but since you already know the website the user is coming from through document.referrer, and you're in your current side you can do:

document.referrer.includes(location.origin);

And if you need to support IE or Opera:

document.referrer.indexOf(`${location.protocol}//${location.host}`) === 0;

Keep in mind this code alone won't do what you're asking. This only works for the referrer. You can then make a combination of this method plus browser history to know whether someone's last visit was on your own site or coming from somewhere else

Upvotes: 2

Related Questions