Utilize JavaScript to activate a new browser tab and monitor its status for closure

When I attempt to open a new tab using JavaScript and track when it is closed, none of the events are being triggered. All the examples I found reference the onbeforeunload event for the current window, not for other window objects.

window.addEventListener('DOMContentLoaded', () => {
    document.querySelector('#youtube-open').addEventListener('click', () => {
        document.yTT = window.open('https://youtube.com', '_blank');
        document.yTT.addEventListener('close', () => {
            console.log('onclose fired');
        });
        document.yTT.addEventListener('beforeunload', () => {
            console.log('onbeforeunload fired');
        });
        document.yTT.addEventListener('unload', () => {
            console.log('onunload fired');
        });
    });
});

Despite no errors appearing in the JS console, the functionality just doesn't seem to be working. Any thoughts on why this might be happening?

Answer ā„–1

Accessing other window instances within a browser is restricted, but one workaround is utilizing local storage (which can be accessed from the previously mentioned events) to store cross-tab data and implementing a polling method in your main tab to retrieve the states.

Answer ā„–2

Achieving the tracking of when the window is closed is definitely possible, but not in the way you may have initially thought.

The document.yTT variable stores the WindowProxy object that is returned by window.open(). Unfortunately, this object does not emit the events that you are trying to capture. However, it does contain a property that indicates whether the window has been closed or not.

If you wish to execute a function when the window is closed, you can follow this approach:

window.addEventListener('DOMContentLoaded', () => {
    document.querySelector('#youtube-open').addEventListener('click', () => {
        document.yTT = window.open('https://youtube.com', '_blank');
        document.yTTInterval = setInterval(() => {
            if (document.yTT.closed) {
                clearInterval(document.yTTInterval);
                executeSomeFunction();
            }
        }, 1); // adjust interval as needed
    });
});

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

perform asynchronous calls within a for loop in a synchronous manner

Having issues with managing asynchronous events in sails.js. Obtaining data from a JSONapi and attempting to insert it into the database sequentially within a for loop. The goal is to maintain the correct order of execution. For simplicity, consider the f ...

Tips on customizing the appearance of React rendering components

<div> <h3>{this.props.product.name}</h3> <h3>{this.props.product.code}</h3> {this.renderColors()} <article> <div da ...

Npm is unable to locate the package.json file in the incorrect directory

Hello, I am currently in the process of setting up webpack. I have all the configurations ready, but when I attempt to execute webpack in my terminal, it looks for the package.json file in the incorrect location. Is there a way for me to modify the path ...

Extract hidden form variables using a function in PHP

Here is the JavaScript function that I have written: function GetCellValues() { var rows = document.getElementsByTagName('tr'); var str = ''; for (var c = 1 ; c < rows.length ; c++) { str += '\n&apo ...

Hold off on refreshing the page until all the $.get calls have finished executing

I am currently using a piece of JavaScript to execute an Ajax call which returns XML data. This XML is then processed, and another Ajax call is made for each "record" found in the XML to delete that record. However, I am facing an issue where the JavaScrip ...

A warning has been issued: CommonsChunkPlugin will now only accept one argument

I am currently working on building my Angular application using webpack. To help me with this process, I found a useful link here. In order to configure webpack, I created a webpack.config.js file at the package.json level and added the line "bundle": "web ...

NodeJs took an unexpected turn

Iā€™m encountering an issue with an http request to forecast.io. When I make a normal request using $.ajax, everything works fine. However, when I try using the ajax-request module, I receive the following output: SyntaxError: Unexpected token u in JSON at ...

Utilize Jquery and MVC 5 to create a reoccurring partial view

I have a button that triggers the loading of a partial view containing a table with all the categories in my system. <input type="button" value="Load Categories" id="btnLoadCategories" /> This loading process is done via a partial view which is in ...

Why does the function yield two distinct outcomes?

I can't figure out why, but when I execute the function (kpis1) by itself, it returns the result (100), however, when I run the function (kpis2) alone, I get the result (97). But when I run both functions together, the results are kpis1=100 and kpis2 ...

Setting a default action for an Ext.Ajax.request error situation

In my application, I frequently make ajax requests using the Ext.Ajax.request method. Often, I find myself skipping error handling for failed requests due to time constraints or lack of interest in implementing fancy error handling. As a result, my code us ...

Sequelizejs establishes a belongsToMany relation with a specified otherKey

I am currently developing an app centered around songs and artists, and here is the database schema I have designed: Each Song can have multiple Artists associated with it, and each Artist can be linked to several Songs as well. This establishes a many-to ...

How can I extract only certain keys from a large JavaScript object while keeping the code concise?

Simply put, I aim to streamline objects by discarding unnecessary keys. Imagine a scenario where a third party API sends back JSON data with numerous attributes that hold no importance to you. obj = { name: ..., id: ..., description: ..., blah: .. ...

I'm currently attempting to determine the total cost of a series of operations, however, I am not receiving any results

Here is the code snippet from my HTML file: <tr> <td><input id="z1" type="number" oninput="calculateSubTotal()"> </td> <td>Shirts - WASH - Qty 1 to 4</td> <td>2.50 ea</td> ...

I'm having trouble getting the aggregation of a child collection to work properly in MongoDB when attempting to apply the $count

Could someone help me troubleshoot my aggregate query? I'm trying to sum the count values for each beacon, but it keeps returning 0. Please let me know if you spot any mistakes in the query. Sample Data [ { ...

What is the best way to fetch data for each specific ID using axios.post when making a URL call?

Utilizing Axios to fetch data from an API and display them as cards in a movie component, I am facing the challenge of enabling users to click on a single movie card and navigate to another page (singlepage.vue) with the corresponding movie ID from the API ...

Setting Default Value for Autocomplete in React

I'm facing an issue with the default value in my autocomplete feature within my React app. Even though I set a default value, when I try to submit the form, it still shows as invalid because it appears to have no value until I manually click on the au ...

JavaScript parsing error occurred

Encountering a parsing error in my JavaScript code when deploying Firebase functions. The error mentions an unexpected token, indicating there might be a character out of place. I've been stuck on this issue for weeks now. Any assistance would be grea ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

User input determines the path of Iron Route in Meteor

A requirement is to execute a function that prompts the user for input and then navigates to that specified value. For instance, if the inserted value is: https://www.youtube.com/watch?v=_ZiN_NqT-Us The intended destination URL should be: download?u ...

Organizing HTML elements based on their class names, especially when an element has multiple classes assigned

Hey there, I've been working on an artist page that showcases multiple artists, each with a portfolio image and some detailed information. My goal is to have buttons at the top of the page that, upon clicking, will sort the artists displayed. To achi ...