この投稿に出くわした人のために、これは onbeforeunload サポートを検出するために使用するコード スニペットです。ブラウザーがサポートしていない場合は、onunload に切り替えます (jquery の使用に注意してください。明らかに必須ではありません)。私の場合、このコード (および少し追加) を使用して、AJAX リクエストがまだアクティブであるかどうかを確認し、ユーザーの移動を停止します。onunload の使用は理想的ではないことに注意してください。ブラウザは引き続きページから移動しますが、少なくとも、データが失われた可能性があり、戻って確認する必要があることをユーザーに警告する機会が得られます。
使用可能なイベントを検出するクロス ブラウザー サポートのために、 https://github.com/kangax/iseventsupportedで利用可能な isEventSupported() 関数を使用していることにお気付きでしょう。
// If the browser supports 'onbeforeunload'
if (isEventSupported('beforeunload', window)) {
$(window).on('beforeunload', function(){
return 'This page is still sending or receiving data from our server, if you recently submitted data on this page please wait a little longer before leaving.';
});
}
// The browser doesn't support 'onbeforeunload' (Such as Opera), do the next best thing 'onunload'.
else {
$(window).on('unload', function(){
alert('This page was still sending or receiving data from our server when you navigated away from it, we would recommend navigating back to the page and ensure your data was submitted.');
});
}