What is the best way to attach an event listener to a child window in vuejs?

After creating a component in vue 3, I found myself in need of a new window, similar to a popup, using the window.open(url, name, config) method. Furthermore, I required a way to execute a function when this child window is closed.

(Please bear in mind that this pertains to interactions between a window object and its parent, not events between child and parent components.)

I attempted to attach event listeners to the popup window; however, these are removed once the URL redirects within the child window.

In the script section of a component, I added a method to launch a new window and perform other tasks upon clicking a button, as shown below:

<template>
    ....
    <button @click="onPositive"></button>
</template>

<script lang="ts">
export default defineComponent({
    methods: {
        onPositive() {
           const popup = window.open(url, name, config) as Window
           popup.focus()

           // Method 1:
           popup.addEventListener('beforeunload' () => {
               console.log("event triggered)
               this.onPopupClosed
           })

           // Method 2:
           popup.onbeforeunload = () => {
               console.log("event triggered)
               this.onPopupClosed
           }
       },

       onPopupClosed() {
            // .....
       }
    }
})
</script>

Despite trying various event listener approaches like the ones mentioned above, I am still unable to trigger the desired behavior.

Here are some observations:

  1. The URL originates from a different source.
  2. Upon closing the child window just before the redirection of the URL, the event is successfully triggered.
  3. This project utilizes Vue.js 3 and TypeScript 5.

Answer №1

If you have control over the popup, there is a way to handle it.

After all the navigation has been completed

<script>
window.addEventListener('beforeunload', () => {
  window.opener.postMessage('popup-closed', '*');
});
</script>

The use of window.opener.postMessage() allows communication between the child window and the parent window that opened it. This method facilitates message exchange between two windows even if they are from different origins (such as different domains, protocols, or ports).

In your parent vue component

... 

// Listening for messages sent by the child window
window.addEventListener('message', (event) => {
  if (event.data === 'popup-closed') {
    onPopupClosed();
  }
});

const onPopupClosed = () => {
  // Handling the event when the child window is closed
  console.log('Popup closed');
};

The usage of

window.addEventListener('message', ...)
in JavaScript enables listening for messages sent from other windows or iframes on a web page. It supports cross-origin communication between different windows or iframes within the same page or across varied domains, protocols, or ports.

Furthermore, the window.opener property constantly points back to the parent window that initiated the child window, despite any intermediate navigations to different URLs. Once a child window is opened via window.open() from its parent, the reference to the parent window remains unchanged throughout the lifecycle of the child window, even during navigations to other URLs before reaching the final destination.

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

Obtain the jQuery dialog's closure event within the $.Ajax completion function

I have developed a custom jQuery plugin that utilizes jQuery Dialog to showcase messages. Specifically, I am using it within my jQuery $.ajax -->done function. My goal is to capture the close event of the Dialog in the .ajax function so that I can redir ...

Utilizing JodaTime with JavaScript (AngularJS): A Comprehensive Guide

I am utilizing DateTime to create Date objects and sending them as JSON to the UI. How can I work with this in JavaScript (specifically AngularJS) and convert it back and forth? For instance, if I need the user to update the time, I should be able to retr ...

Click event for jQuery horizontal accordion

I'm attempting to create a simple horizontal accordion-style element. My setup includes three 'banner' divs and three 'area' divs. Ideally, when I click on a banner, the corresponding area should animate - expanding in width to au ...

Leveraging VueJS: Communicating between components via event bus

Currently, I am utilizing VueJS and aiming to activate a method within a .Vue component using the eventbus. The eventbus is functioning properly, and I followed the instructions provided in this informative article: https://example.com/vuejs/event-handling ...

"Sorry, but it seems like jQuery Ajax isn't recognized as

In my setup, each row of a table looks like this: <tr id="ID" class="company_row">...</tr> Along with that, there is a modal: <div id="company_list_modal"class="modal"> <p>TEST</p> </div> Upon clicking on a table ...

Issues with JavaScript functionality arise when a modal is loaded using AJAX and TWIG

I'm experiencing an issue with my Javascript. I've created a Javascript modal function that uses AJAX to retrieve content, and then the innerHTML function places that content into the modal. While the modal displays the content correctly, the Jav ...

What is the best location to store reusable backend scripts in a Node.js project?

In my Nodejs project, I am working on creating a JavaScript file that is not a middleware. This file will contain a function that takes a value as input and produces an output using module.exports. I am currently deciding on the best location to store this ...

Custom attributes in AngularJS allow developers to add additional behavior

I'm a beginner in the world of angularjs. I was curious about why the custom attributes that angularjs adds to an html element don't cause any errors? Like <div ng-if='true'> Furthermore, is it within our capabilities to create o ...

How can I reattach a click event to cloned elements in Angular2?

I've implemented a table list with the use of *ngFor. Each list item includes a hidden details div and a button to show the details. Following the list items, outside of the table div, there is an empty div. Upon clicking the show details button for e ...

Before the async function, make sure to set the value using React's useState

Exploring the world of react context api for the very first time. Below is my react code utilizing the context api: const [valChanged, setValChanged] = useState(false); async function modalSave() { await setValChanged(true); // STEP 1 await o ...

When using the CDN import version, React does not render components or code

Unfortunately, I am unable to progress with studying React due to encountering a basic issue. Please excuse my lack of experience, no need to judge harshly. The message is not displaying, although the code itself is straightforward; I am perplexed as to wh ...

trouble with reversing arrays in VueJs

When using the Facebook Graph API to receive message conversations, I encounter a need to reverse the data. In the computed function reverseChat, attempting to return this.chat.data seems to work fine. However, when trying JSON.parse(this.chat).data.rever ...

Ensure that an input field on the PHP form is required

Currently working on a form with multiple input fields. I'm wondering if there's a way to prevent the form from being submitted to the server if a specific field is left empty. I'd like to use a JavaScript pop-up box to notify the user inst ...

Tips for choosing and emphasizing specific lines in a dxf document with the help of three.js, dxf-parser, and three-dxf

Incorporating both the dxf-parser and three-dxf libraries, I am working on a webpage to display dxf drawings with the help of the three.js library. Although I was successful in loading the dxf file onto the webpage, I encountered difficulties in highligh ...

Is there a way to input atypical day and time text into an XDate object?

In order to provide further context; we are dealing with a unique textual representation of time and date that varies significantly and requires conversion into an XDate () object (potentially multiple XDate objects). It's important to clarify that I ...

Ways to allocate a random color within an array?

Hi there, I'm trying to create chips with random colors from an array in my code. I attempted to use a color string array and assign them to the chips one after the other, but it didn't work as expected. Any suggestions on how I can achieve this? ...

Choosing elements from an array - Utilizing the filter technique in JavaScript

Today, there was a question raised about selecting specific elements within an array from a certain index to the end of the array. This got me thinking about how I could achieve this using the filter method. One suggestion was to use the slice method, whi ...

Tips for safely executing an SQL query with electron.js

I have a new project where I need to interact with an SQL database on the local network, but it's not located on the same system I'm working on (not SQLExpress). So far, I've figured out how to collect user input on a webpage and send that ...

Collapsing tabs feature in Bootstrap 4

I am working on a project with Bootstrap 4 Tab. My goal is to initially hide all tab contents and then show them when the corresponding tab is clicked. I achieved this by removing the active class from the tab-pane div. However, I encountered an issue wher ...

Understanding the meaning of `.then()` in Excel JavaScript involves recognizing its function

Excel.run(function (context) { var sheet = context.workbook.worksheets.getItem("Sample"); var range = sheet.getRange("B2:C5"); range.load("address"); return context.sync() .then(function () { ...