fefe
fefe

Reputation: 9055

How to capture on browser open new tab the target url

Is it possible to catch the attribute of hyperlink with JavaScript or Jquery on browsers open new tab event?

lets say I have a hyperlink <a href="http://example.com/something">MyLink</a> and using right click on link and opening new tab should alert first "http://example.com"

Upvotes: 2

Views: 2686

Answers (2)

Grinn
Grinn

Reputation: 5543

Ok, so this is the best that I can come up with but it ain't pretty.

Have all the links on the page point to another page (we'll call it redir.html). redir.html is passed a parameter via the URL that defines what page it should then open, like redir.html?page=www.example.com/something. redir.html then executes whatever JavaScript you want, perhaps only if it was opened in a new tab/window. This can be detected by checking to see if window.history.length === 1.

redir.html:

<script>
function getParameter(param) {
            var val = document.URL;
            var url = val.substr(val.indexOf(param))  
            var n=url.replace(param+"=","");
            return n;
}
var page = getParameter("page");
if(window.history.length === 1)
{
    alert("I opened in a new tab or window");
}

window.location.href = page;
</script>

Example anchor tag on source page:

<a href="redir.html?page=http://example.com/something">My link</a>

(I got the getParameter function from this SO post.)

Upvotes: 2

Soroush Falahati
Soroush Falahati

Reputation: 2327

I think this is only possible with writing a browser extension. You cant control this type of things with JavaScript.

Upvotes: 2

Related Questions