0

I have created two hyperlink in which when I click the hyperlink, it should open a new tab in the browser with the corresponding link webpage content, I have done that by using window.open feature,Its working fine, But the problem is that say when I click the hyperlink for the very first time it will open up a new tab, Again when I click the same or the second hyperlink it is opening another tab within the browser, instead If the current opened tab is still opened I need it be reloaded with that tab itself, If none of the tabs were opened then it should open a fresh new tab.

Is this can be done through JavaScript

My Code is as given below

JSFiddle

html

<a href="javascript:void(0);" onclick="openTab('http://stackoverflow.com')">StackOverflow</a>

<a href="javascript:void(0);" onclick="openTab('https://github.com')">GitHub</a>

script

function openTab(link) {
    window.mypopup = window.open(link);
}
Alex Man
  • 4,746
  • 17
  • 93
  • 178

2 Answers2

2

Edit: I changed my whole answer, since I saw there is a cleaner way you will prefer :

var w;

function openTab(link) {
if (typeof(w) === 'undefined')
    w = window.open(link);
else {
    w.location.href=link;
}

}

See this topic where this problem has already been solved.

Cheers

Community
  • 1
  • 1
bviale
  • 5,245
  • 3
  • 28
  • 48
  • cant we do anything like reloading with the new link, instead of closing and opening – Alex Man Mar 19 '15 at 13:01
  • Changed my answer, take a look at it ;) – bviale Mar 19 '15 at 13:06
  • Thanks for your answer, but Tolokoban answer seems to be the clean way I guess – Alex Man Mar 19 '15 at 13:10
  • But my solution is not a good one: it works only with Firefox. Sorry. Maybe **bviale**'s solution can work with Chrome. – Tolokoban Mar 19 '15 at 13:32
  • Unfortunately Chrome seems to be unpermissive on this subject. My solution does not work on Chrome, neither does the "close() then open()" trick – bviale Mar 19 '15 at 13:51
  • window.open(link, "MyTab"); is working for my project for all browsers even IE9,10,11, may be in jsfiddle it is because of CORS – Alex Man Mar 19 '15 at 14:21
1

You can use TARGET to use the same tab for different URLs.

http://jsfiddle.net/07hh3z2n/2/

This is the second argument of window.open.

window.open("http://en.wikipedia.org", "MyTab");
Tolokoban
  • 2,297
  • 14
  • 17