`visibilitychange` firing as "hidden" and not "visible" for new window initial load
Asked Answered
K

1

6

I am launching a new tab and trying to add a visibilitychange handler for the window in order to add unload behavior, since all the docs recommend that over onunload and pagehide. My plan was to attach the listener, and when the document's visibilityState changed to hidden, whether by explicitly closing it or just navigating away or something, to close the tab and have the parent window trigger some functionality.

The code is roughly as follows:

var testTab = window.open(myPath, 'testTab');
testTab.addEventListener('visibilitychange', function () {
  if(testTab.document.visibilityState === 'hidden'){
    onHidden();
  }
  else {
    onVisible();
  }
});
testTab.focus();

However, when the new tab is opened, the listener fires with the hidden visibilityState before any content of the window is loaded. The event does not fire again after that, even by the time the window has finished loading and rendering. If I then hide the tab (by any means, eg. open the original tab in the same window), the event fires with hidden as expected. Then going back to the opened tab will trigger the event as visible, as expected.

How come the page doesn't seem to have the correct visibilityState on the initial load? I could make sense of it if it started hidden, and then transitioned to visible once it finished rendering or something like that, but it being hidden only on initial render seems very fishy; I have to assume I'm doing something wrong.

Edit: Out of curiosity, I tried using pagehide and it suffers from the same problem. It is being triggered immediately when the new window first opens, before any content has been loaded. I'm not sure where I'm going wrong.

Edit2: unload/beforeunload do work as expected on page load (ie. they don't fire at all), and do properly fire on unload (duh.) but don't share the ability to hook into other forms of visibility loss, and is generally advised against in everything I could find, especially because of its mobile support.

Koal answered 7/6, 2022 at 20:29 Comment(0)
H
0

try this code.

var testTab = window.open(myPath, 'testTab');

function addVisibilityChangeListener(tab) {   tab.document.addEventListener('visibilitychange', function () {
    if (tab.document.visibilityState === 'hidden') {
      onHidden();
    } else {
      onVisible();
    }   }); }

testTab.addEventListener('load', function () {   addVisibilityChangeListener(testTab); });

testTab.focus();
Hirsutism answered 19/6 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.