简体   繁体   中英

Refresh button/F5 send directly to the controller(mvc) when have window.onbeforeunload in a javascript

I need to call a controller when user press Close button, so I did this:

In a javascript:

document.onkeydown = fkey;
var refresh = false;

function fkey(e) {
    e = e || window.event;
    key = (document.all) ? e.keyCode : e.which;
    if (key == 116) {
        refresh = true;
    }
}

window.onbeforeunload = function () {
      debugger;
      if(!refresh){
         callController();
     }
}

function callController() {
    $.ajax({
        url: "/Controller/FunctionX",
        type: "POST",
        async: true,
        cache: false,
        data: { 'refresh': refresh},
        success: function (jsonResults) {
        },
        error: function () {
        },
        complete: function () {
        }
    });
};

The problem is: When I press F5 or "refresh button", and try to debug this code, the action goes directly to the Controller (FunctionX) without pass/stop in this .js

Any idea? Thanks

Change your fkey function to this instead

function fkey(e){
    e = e || window.event;
    if (e.code === 'F5') {
        refresh = true;
    }
}

You can see a full example here and if you watch the console you can see callController is not called right before the reload. You can test non-F5 reloads but clicking "Run" in jsfiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM