2

I'm using the code below with window.open to open a new link (same origin) in a new tab. If a tab with the new link is already open, the open tab should be focused instead.

This is all working fine, the focused tab is however always refreshed when it gains focus by this. How can I stop the focused tab from refreshing?

window.open(`./${_id}`, `module_${_id}`);
SeReGa
  • 1,219
  • 2
  • 11
  • 32
coemu
  • 195
  • 1
  • 11
  • 1
    Stop propagation? This may be helpful for you: https://stackoverflow.com/questions/387736/how-to-stop-event-propagation-with-inline-onclick-attribute – SeReGa Dec 16 '21 at 22:38
  • Which event will be created by this and how can I intercept it? – coemu Dec 16 '21 at 22:45
  • Most likely, the event is not created by this, but this is called by some event. Isn't it? (probably click) – SeReGa Dec 17 '21 at 21:46

1 Answers1

2

Check if the window is closed orelse use focus(), this should not refresh the page.

    var windowObject = null; // global variable
    
        function openURL(url) {
          if(windowObject == null || windowObject.closed) {
            windowObject= window.open(url);
          } else {
            windowObject.focus();
          }
        }

<button value="Check" onClick="openURL('https://www.google.com')"></button>
Mana S
  • 509
  • 2
  • 6
  • I see this working if it is always the same tab who opens the new tabs. But when opening the link from a third tab, it will still open the link in a new tab. – coemu Dec 16 '21 at 22:49
  • 3
    @Alrick Unless you are running this in a browser extension you have no way to check other tabs from inside a single page window. You might be able to use PostMessage API to communicate between windows you control – charlietfl Dec 16 '21 at 23:07