Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onbeforeunload not firing in Chrome but working in Firefox

I have a main window and a pop up window. Popup window is created on the main window.

Like parent.php is the main window. On this page, I have a JavaScript function to reload the page as below:

function popUpClosed() {
  window.location.reload();
}

We can open popup window from parent.php. Now I want to execute popUpClosed() function on parent.php from popup window when we close / navigate the popup window.

I have tried following methods to achieve the same.

Method 1

window.onunload = window.onbeforeunload = function() {
  if(window.opener && !window.opener.closed) {
    window.opener.popUpClosed();
  }
};

Method 2

window.onbeforeunload = Call;

function Call() {
  if(window.opener && !window.opener.closed) {
    window.opener.popUpClosed();
  }
}

Method 3

window.onpagehide = function() {
  window.opener.popUpClosed();
}

Everything is working is fine in every browser except Google Chrome. Chrome is not firing any of the function.

However, this is happening from last 2-3 days. Earlier all the things was working well in Chrome. (Might has been caused due to the latest Chrome updates)

Any suggest will be appreciated.

like image 223
vitorio Avatar asked Nov 26 '22 14:11

vitorio


1 Answers

Latest google Chrome has a problem with window.opener. window.opener navigation inside a beforeunload/unload handler is ignored in the latest version. However there is a workaround for this. Try below code:

var btn = document.getElementById("btn");

function detectClick(event) {
  var wind = window.open('urlhere', 'name', 'width=' + screen.width/2 + ', height=' + screen.height/2);
  wind.onbeforeunload = function(){ 
    popupClosed(wind);
  }
}
btn.addEventListener("click", detectClick, false);

function popupClosed(wind) {
  setTimeout(function() {
    wind.opener.location.href = window.location.href;
  }, 0);
}
<input id= "btn" type="button" value="open popup" />

THIS CODE WON'T EXECUTE HERE ON STACK OVERFLOW BUT WILL WORK IN BOTH: Chrome AND Mozilla Firefox WHEN EXECUTED THROUGH jsfiddle OR SERVER.

Here is a working code: jsfiddle

here is the link of bug report that confirms beforeunload/unload handler issue.

like image 90
Aniket Sahrawat Avatar answered Nov 29 '22 02:11

Aniket Sahrawat