Richard N
Richard N

Reputation: 925

How to open a link in the first open new browser tab

I know that this might not be possible.

Lets say I have a list of say 50 hyperlinks. The default behavior is to open the links in a new tab when clicked. But I want to prevent the user from opening 50 tabs if he/she clicks on all 50.

So is there any way to create a hyperlink which when clicked,

  1. Opens the first link in a new tab
  2. Subsequent links are opened in that same tab(instead of a new tab)

If it helps, Chrome will be the browser that we would use for this. Is there any HTML.JS, Chrome trick that we can use? Thanks.

Upvotes: 0

Views: 926

Answers (2)

Jacob
Jacob

Reputation: 1

This works because it changes the URL of one window if it is opened to the link that the user clicked.

<html>
<head>
<title>
Search Engines
</title>
<script>

opened = false ;

function openMyLink(linkToOpen) {

    if (opened === false) {

        openWindow = window.open(linkToOpen,"_blank") ;
        opened = true ;
        openWindow.addEventListener("beforeunload",function () {opened = false ;}) ;

    }

    else {

        openWindow.location.href = linkToOpen ;

    }

}

</script>
<style>
a {

cursor : pointer ;
color : blue ;
text-decoration : underline ;

}
</style>
</head>
<body>
<h1>
Search Engines
</h1>
<br><a onclick="openMyLink('http://www.google.com/') ;">Google</a>
<br><a onclick="openMyLink('http://www.bing.com/') ;">Bing</a>
<br><a onclick="openMyLink('http://www.yahoo.com/') ;">Yahoo</a>
</body>
</html>

Upvotes: 0

David R
David R

Reputation: 15667

Add this snippet to your code, and check.

var a = document.getElementsByTagName("a"); 
for (i=0;i<a.length;i++) { 

        if (a[i].target="_blank") { 
            a[i].target="_self" 
        } 
                         
}

Upvotes: 2

Related Questions