Unfortunately, I have to present this as a response because I am unable to include images in comments. Nevertheless, upon examining the scenario, I did not observe this particular behavior.
- Upon verification, it is clear that the
window.uuid
variable is not present within window
.
- After adding the event listener, the initial output of registering it shows the expected first value of
undefined
.
- Subsequently, when clicking outside of the tab (triggering the first
visibilitychange
event), both the second undefined
and the assigned value for window.uuid
are logged from the listener.
- Moving back into the tab triggers the second
visibilitychange
event, resulting in the uuid being logged twice.
- Entering
window.uuid
into the console reveals the global uuid value.
https://i.sstatic.net/9PUvf.png
The potential issue might stem from how you are linking the event listener.
UPDATE:
Testing with the following webpage example:
<html>
<head>
<script>
window.addEventListener("visibilitychange", function(e) {
console.dir(window);
console.log(window.uidd)
window.uidd = window.uidd || (new Date).getTime() + Math.random()
console.log(window.uidd)
})
</script>
</head>
<body></body>
</html>
This behavior does manifest itself. To access the property correctly, you should employ this.uuid
instead of window.uuid
, despite the fact that inspecting window
will display the .uuid
property.
Coincidentally, when replacing your test code with this fixed assignment:
window.addEventListener("visibilitychange", function(e) {
window.foo = window.foo || "bar";
})
it indeed functions as intended, and I can directly view the anticipated value of window.foo
in the console.
I share your curiosity and have reached out to the Chrome team for further insights. I'll provide an update to this explanation if they do not respond promptly.