What was the functionality of visibilitychange implemented for?

Here is my query:

window.addEventListener("visibilitychange", function(e) {
  console.log(window.uidd)
  window.uidd = window.uidd || (new Date).getTime() + Math.random()
  console.log(window.uidd)
})

However, if you open the console for the first time, you will see:

undefined
124124214124124.124

window.uidd // undefined

Why does the last string show undefined?

Answer №1

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.

  1. Upon verification, it is clear that the window.uuid variable is not present within window.
  2. After adding the event listener, the initial output of registering it shows the expected first value of undefined.
  3. 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.
  4. Moving back into the tab triggers the second visibilitychange event, resulting in the uuid being logged twice.
  5. 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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with submitting input fields that were dynamically added using jquery

I created a table where clicking on a td converts it into an input field with both name and value. The input fields are successfully generated, but they do not get submitted along with the form. In my HTML/PHP : <tr> <f ...

Vue.js 2 view failing to update after modifying data in Vuex state

Greetings, I am currently working on developing a table to monitor the validation status of multiple items. Below is the VueX store configuration: mutations: { ..., set_scaninfos: function (state, scaninfos) { Vue.set(state, 'scaninfos&a ...

Is it possible to obtain the output of a JavaScript file directly? (kind of like AJAX)

My previous experience with AJAX involved a server-side language like PHP generating xHTML with attached JS. The JS would then query another file using parameters set in either GET or POST. The output of the queried file would be returned to the JS, which ...

Switch up the CSS variable within an embedded iframe

I'm in a predicament with a specific issue. I am currently utilizing Angular to incorporate an Iframe. Let's imagine the angular app as A and the Iframe as B. B is being loaded within A. Within B, I have utilized CSS variables to define colors. I ...

Vue.js caution about "Unnecessary non-emits event listeners" alert for events within RouterView

Is there a way for me to trigger events from my child components and have them reach the top-level App.vue component even though I am using a RouterView to render the child components in the App.vue template? <template> <Navbar /> <c ...

Updating a value in an array in Angular using the same ID

I have an array of buildings that looks like this: const buildings = [ { id: 111, status: false, image: 'Test1' }, { id: 334, status: true, image: 'Test4' }, { id: 243, status: false, image: 'Test7' }, { id: 654, stat ...

I feel overwhelmed and confused by Node, Express, domains, and uncaught exceptions

After hours of research on exception handling in Node, I've come to understand the drawbacks of using uncaughtException. It's clear that shutting down the process can prevent any potential "unknown state" scenarios where anything may happen. The ...

Creating HTML input elements dynamically using Javascript

<body> <form action="insertquestion.php" method="POST"> <script> function generateInputs(){ var prefix = "answer"; var number = 1; for(var i = 0; i < 5; i++){ ...

What is the process for accessing the content of a URI on the console page?

let request = new XMLHttpRequest(); request.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json'); request.onload = function() { console.log(request.responseText); }; request.send(); I am continuously seeing t ...

Display detailed images upon hovering

Top of the morning to everyone. I'm in search of a way to display higher resolution images when hovering over lower resolution ones. I want to create a rule or function that can handle this dynamically without manually adding hover effects and changi ...

An easy way to export static images in Next.js

Whenever I try to export my nextjs app, an error message pops up stating that image export is not supported on static websites. Error: The default image loader in Next.js cannot be used with next export. Possible solutions: - Use next start to run a serv ...

Collaborative Desktop & Web Application powered by Javascript REST/Ajax

Currently, my node.js back-end is seamlessly working with a web-based JavaScript client by sending AJAX requests. However, I am now contemplating creating a compact desktop version of the JavaScript client using solely JavaScript, specifically leveraging ...

Is it possible for Typescript to allow extracted interfaces while excluding properties from another interface?

I've been searching for information on the specific features of this. Despite my efforts on Google, I have been unable to find the details. Any help would be greatly appreciated! interface Numbers { number: number; number2: number; number ...

Node.js: App crashed, standing by for file changes to initiate restart

While I was in the middle of a nodejs course on Udemy, I encountered an issue where the code suddenly started breaking and throwing errors. Even after attempting to replicate the instructor's code, the problem persisted. I sought guidance from this a ...

Is there a memory leak causing Node.js memory growth in the (system)?

I have come across a peculiar memory leak in our live environment, where the heap continues to grow due to (system) objects. Heap snapshot Here is a memory dump showing a spike in memory usage up to 800MB: https://i.sstatic.net/vvEpA.png It seems that t ...

Transform the values in an object using TypeScript without losing type information

Can TypeScript map an object's values to another type based on the actual type of each entry in the result? To better explain my goal, consider the following scenario: const obj = { a: 1, b: true, c: "foo" } const result = toFunctions(o ...

What is the technique for accessing dynamic object properties in Javascript?

I am dealing with a dynamic object where the property values change based on different data sets. For example: MyObj = { country:"Ind", Place:"Pune"} Now, I have a data value that determines which property value I need to retrieve. var MyArr = this.Filt ...

Creating a phonecat application using Angular on a node server

As a newcomer to Angular, I am currently in the process of setting up the Angular phonecat application. To begin with, I downloaded the code from this location: https://docs.angularjs.org/tutorial/ After that, I installed Node.js on my system. Now, I a ...

In Chrome, the computed style of background-position is returned as 0% 0%

Let's say I have an element and I am interested in finding out its background-position: To achieve this, I use the following code snippet: window.getComputedStyle(element).getPropertyValue('background-position') If the value of background ...

Is there a way to effortlessly refresh the WooCommerce cart and receive updated HTML content all in one go?

I am currently working on a customized "mini-cart" that mimics the functionality of the main cart page, including options to adjust quantity, remove items, enter coupons, and remove coupons. I have set up the cart to submit changes via Ajax by listening fo ...