vitorio vitorio - 16 days ago 6
Javascript Question

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.

Answer

You can try the below code:

I have created the common function for open the POP up window:

function PopupCenter(url, title, w, h) {
        var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
        var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

        width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
        height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

        var left = ((width / 2) - (w / 2)) + dualScreenLeft;
        var top = ((height / 2) - (h / 2)) + dualScreenTop;

        child = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

        if (child.focus) {
            child.focus();
        }
    }

For checking the child window closed or not I am using the setInterval function and check the interval like below:

function checkChild() {
        if (child.closed) {
            //alert("Child window closed");
            clearInterval(timer);
            location.reload();
        }
    }

DEMO

Comments