Shiv Kumar Ganesh
Shiv Kumar Ganesh

Reputation: 3825

onbeforeunload unbind not working on IE

I am not able to cancel the onbeforeunload in IE. I am not sure what is the issue but setting it to undefined does not have an effect. I want to unbind the event under certain condition. In all other browser it works though.

The code is mentioned below:-

$(document).ready(function(){

    window.onbeforeunload = function(){
        return '';
    }

    window.addEventListener('message', function(e) {
    if(e.data==="UNBIND_UNLOAD"){
        window.onbeforeunload = undefined;
        window.close();
        }
    } , false);

    $('#sendParentMessage').click(function(){
    window.onbeforeunload = undefined;
        window.opener.postMessage('Hi Child How are you!!!','*');
    });
});

Upvotes: 0

Views: 39

Answers (1)

epascarello
epascarello

Reputation: 207501

Add the events the proper way and remove them

var unloadFunction = function () {
  return "test";
}
window.addEventListener('beforeunload', unloadFunction)

window.addEventListener('message', function(e) {
if(e.data==="UNBIND_UNLOAD"){
    window.removeEventListener('beforeunload', unloadFunction)
    window.close();
    }
} , false);

or change the code to use a check inside the function instead of removing it

var isActiveCheck = true
var unloadFunction = function () {
  return isActiveCheck ? "test" : undefined;
}
window.addEventListener('beforeunload', unloadFunction)

window.addEventListener('message', function(e) {
if(e.data==="UNBIND_UNLOAD"){
    isActiveCheck = false
    window.close();
    }
} , false);

Upvotes: 1

Related Questions