Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a browser tab is already open so I don't make extra tabs

When a user adds an item to our shopping cart it opens our store in a new tab. Different websites oddly enough.

I would like to check if the tab is already open and then repopulate it it with the second item instead of opening another tab with the updated cart.

Is there a way to check this with js? I imagine I can track that we opened the tab but I don't see how I can confirm that it wasn't closed in the time between adding items to the cart without doing some ajax requests pinging both pages etc. Which seems like overkill.

So simply how do you check if a browser tab is already open?

Edited with a solution: First:

var tab = window.open('http://google.com','MyTab');

Then:

if(tab) {
  var tab = window.open('http://yahoo.com','MyTab');
}
like image 716
BobB Avatar asked Nov 16 '12 22:11

BobB


People also ask

How do I stop the same website from opening multiple tabs?

You cannot (and should not) do that. User can always just open use another browser or another computer to open another view onto the web site. So, basically you cannot ever prevent this. Your web-site should be able to handle multiple tabs viewing the same state.

How do I stop so many tabs opening?

Keep an eye on the number of tabs that you're opening, and routinely close tabs that you aren't using. You can use the CTRL + W (CMD + W) keyboard command to quickly close through tabs, without aiming for any little red Xs. You can also right-click a tab to “Close Tabs to the Right” or “Close Other Tabs.”

How do you check if a browser tab is currently active or not?

The Page Visibility API: It lets the developers know if the current tab is currently active or not. When the user switches to another tab or minimizes the window, then the pagevisibilitychange event gets triggered. This API added these properties to the document object. document.


2 Answers

window.open has the following parameters: var tab = window.open(url, name, specs, replace) As long as you use the same name the url will be loaded into that window/tab.

If you wanted to keep the descriptor/reference (tab above), that window.open returns, once the user refreshes the page, that reference is lost.

like image 84
Candide Avatar answered Oct 01 '22 18:10

Candide


I think your best bet could be session storage / local storage, but it works only in newer browsers.

like image 43
tonino.j Avatar answered Oct 01 '22 16:10

tonino.j