[Vuejs]-How to properly add an event listener to a child window in vuejs?

0👍

If the popup is under your control, you can do something like this.

In the final place, when all the navigation is done

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

window.opener.postMessage() is a method that allows communication between the current window (child window) and the window that opened it (parent window). It provides a way to send messages between the two windows, even if they are from different origins (i.e., different domains, protocols, or ports).

In your parent vue component

... 

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

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

window.addEventListener('message', ...) is an event listener in JavaScript that allows you to listen for messages sent from other windows or iframes in a web page. It enables cross-origin communication between different windows or iframes on the same page or across different domains, protocols, or ports.

One more thing is the window.opener property always refers to the parent window that opened the child window, regardless of any intermediate navigation to other URLs. Once a child window is opened using window.open() from the parent window, the reference to the parent window remains the same throughout the child window’s lifetime, even if the child window navigates to other URLs before go through final destination.

Leave a comment