Home > front end >  How to switch to a specific browser tab programmatically using JavaScript with same origin?
How to switch to a specific browser tab programmatically using JavaScript with same origin?

Time:04-30

I'm using google chrome browser and trying to switch the focus between two browser tabs whose origin is same using JavaScript.

I open a tab say tab_1 using

window.open("www.example.com/{data}","_blank");

And then I open some new tabs say tab_2, tab_3 and tab_4 in the same browser and go back to the first tab tab_1 (www.example.com/{data}). Then I do some work on tab_4 and after clicking on the submit button, I close the current tab using window.close() and the focus goes to tab_3 but I want to shift the focus to tab_1 instead.

So, how can I change the focus of the current browser to a specific tab which I opened using window.open() statement?

If it's not possible using Javascript, please help me with any other solution to achieve this.

CodePudding user response:

In the window that you open with window.open() you have the window.opener option, that is the instance that open that tab. But you can't switch between tabs with JavaScript. Wat you can do, after window.close(), is reload the current tab to the destination you want.

CodePudding user response:

If you use in a button
<button onclick="window.close();">Close</button>
if you use in function
function closeWin() {
  myWindow.close(); 
}
But it will only work when you open a window through your code like this
function openWin() {
  myWindow = window.open("", "myWindow", "width=200, height=100");
}
You can't close the current window that was open by browser. beacuse browser don't give permission.
  • Related