简体   繁体   中英

window.onbeforeunload not firing in Layout.cshtml

Layout.cshtml:

        window.onbeforeunload = function () {
            alert("navigating away");
        };

Not firing, can you help?

You should not alert anythnig inside the onbeforeunload function. You should return a string:

<script type="text/javascript">
    window.onbeforeunload = function () {
        return "navigating away";
    };
</script>

The way this string will be presented to the user is user agent dependent. You have absolutely no control over it. But in most cases it will appear as a confirmation popup.

As Darin mentioned you can only return a string.

When onbeforeunload is called, it will take the return value of the handler as window.event.returnValue and then parse the return value as a string (unless it is null) False is parsed as a string, the dialogue box will fire, which will then pass an appropriate true/false.

There is no way of assigning false to onbeforeunload.

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