Matt Le Fleur
Matt Le Fleur

Reputation: 2856

Detect whether a window was opened from the same website

If I make a link to another part of the site e.g.

<a href="foo.html" target="_blank">Link</a>

I want to be able to tell in the new window if the user has come via that link, or if they have come directly to that url via a different route. Is that possible?

This is because, if they came from the same site, I can use window.close();, but not if they came via a different route.

Upvotes: 1

Views: 72

Answers (1)

Jai
Jai

Reputation: 74738

In this case you can use document.referrer:

if(document.referrer){
    // close the window here
    console.log('loaded via navigation')
}else{
    console.log('no navigation');
}

or you might want to get the domain name from the referrer:

function virtualURL(url) {
    var a=document.createElement('a');
    a.href=url;
    return a.hostname;
}

if(virtualURL(document.referrer)  === window.location.hostname){
    // close the window here
    console.log('loaded via navigation')
}else{
    console.log('nope');
}

Here in the above code virtualURL(document.referrer) will return the hostname of the last visited page. So, you can match that with the current application's host name, if they match then you can close the window.

Upvotes: 2

Related Questions