Domanda

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');
}
È stato utile?

Soluzione

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.

Altri suggerimenti

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

All you need is to save a reference to the opened tab that you can relate with some id that will make sense to you... Then when you need to reopen it again just use the saved reference from there you can access your parent or opener window from window.opener. Also to know when the child window is closed there is a default browser event "beforeunload" that when called can remove the window from your reference object in your parent so you know that you have to reopen it not just focus it.

I gone through each steps and I came up with some points. I tested it on IE. It did not worked as expected if you use URL like (htp://www.google.com) and it worked if you use your domain page.

While it worked well for Firefox and chrome.

Following example does not work:

<script type="text/javascript">
    function myfunction1() {
        window.open('http://www.google.com', 'f');
    }
    function myfunction2() {
        window.open('http://www.yahoo.com', 'f');
    }
</script>
<body>
    <form id="form2" runat="server">
    <div>
        <a href="#" onclick='myfunction1();'>myfunction1</a> 
        <a href="#" onclick='myfunction2();'>myfunction2</a>
    </div>
    </form>
</body>
</html>

And Following example works:

<script type="text/javascript">
        function myfunction1() {
            window.open('WebForm1.aspx', 'f');
        }
        function myfunction2() {
            window.open('WebForm2.aspx', 'f');
        }
</script>
<body>
    <form id="form1" runat="server">
    <div>
        <a href="#" onclick='myfunction1();'>myfunction1</a>
        <a href="#" onclick='myfunction2();'>myfunction2</a>
    </div>
    </form>
</body>
</html>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top