Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onbeforeunload fires in IE for partial postback events

I want to warn users when the refresh or press back button of the browser if they have entered some thing in text boxes. So I have used window.onbeforeunload function to do it.

window.onbeforeunload = function () {
    if (if user hasn't entered any thing) {
        return;
    }
    return 'Entered data will be lost.';
};

this javascript code works fine in Firefox and chrome. But in IE this function fires for buttons with partial post backs. Any solution to overcome this problem in IE ? Thanks :)

  • It's happen because of Bug in IE
like image 935
cp100 Avatar asked Feb 13 '13 06:02

cp100


1 Answers

window.onbeforeunload function not execute in IE correctly. Because some partial postbacks are also considered as "Trying to leave the page". If a link on the page has href="javascript:...." (ASP.Net LinkButton is rendered like this), IE will incorrectly fire the window unload event when the link is clicked. so, I kept a dirtyflag variable and added

var __ignoreDirtyFlag = false;

$(document).ready(function () {
    if ($.browser.msie) {
        $('[href^="javascript:"]').bind('click.ignoreDirtyFlag', function () {
            __ignoreDirtyFlag = true;
        });
    }
}); 

now when page is loaded, for links started with href^="javascript:" will assigned that function. when link is clicked then it make __ingoreDirtyFlag variable true; then added

window.onbeforeunload = function globalWindowUnload() {
    if (!__ignoreDirtyFlag && isDataFilled == true) {
        return "You have unsaved changes on this page. If you leave this page, those changes will be lost.";
    }
    __ignoreDirtyFlag = false;
    return;
};

if there is any asp update panels you have used in your page, above function binding to the link will be removed. so we have to bind function to the links again when update panel get refreshed.

so,

function foo() {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}

function endRequestHandler(sender, args) {
    // Do your stuff
    if ($.browser.msie) {
        $('[href^="javascript:"]').bind('click.ignoreDirtyFlag', function () {
            __ignoreDirtyFlag = true;
        });
    }
}

and

for body tag onload method, I assinged foo() method. <body onload="foo()">

this hack is working fine with IE and all the browsers :) thanks

like image 63
cp100 Avatar answered Sep 26 '22 16:09

cp100