Is there any way to shift to previous browser tab using javascript?

442 Views Asked by At

Im working on a VBCS application and i have a requirement to download files onto a new tab.

Im running an application, and after a few operations I end up at the last tab (circled in black). I need to close the red circled tab because it is a duplicate of the blue circled tab. Is there any way i can go back to the red tab and call

window.close()

on it? All the tabs are being opened through my application only. IS it even possible to navigate back to the tab? Also i cannot close the blue circled tab because even though the red circled tab is a dulicate of it, the red tab is reloading the page and the blue tab is already loaded page.

Any help is very much appreciated. Thanks.

1

There are 1 best solutions below

0
IT goldman On

You can communicate between the tabs using localStorage (actually there might be even a better API for this BroadcastChannel ). Anyway, this is a sketch of a solution which is open for some bugs but if you like it , it can be improved.

<h2>page 1</h2>
<button onclick="close_others();">close others</button>
<script>
    window.id = Math.random();
    var key = "close-but-me"

    function close_others() {
        localStorage.setItem(key, window.id);
        window.setTimeout(function() {
            localStorage.removeItem(key);
        }, 2000)
    }

    setInterval(function() {
        console.log(localStorage.getItem(key))
        if (localStorage.getItem(key) && localStorage.getItem(key)!=window.id) {
            window.close();
        } 
    }, 1000)
</script>
<h2>page 2 - SAME code</h2>

<button onclick="close_others();">close others</button>
<script>
    window.id = Math.random();
    var key = "close-but-me"

    function close_others() {
        localStorage.setItem(key, window.id);
        window.setTimeout(function() {
            localStorage.removeItem(key);
        }, 2000)
    }

    setInterval(function() {
        console.log(localStorage.getItem(key))
        if (localStorage.getItem(key) && localStorage.getItem(key)!=window.id) {
            window.close();
        } 
    }, 1000)
</script>