window.onbeforeunload = function (event) {
// I need to call an API here but the window is closing
// before making that HTTP call
parent.API.LMSFinish("").then(function () { })
};
是否有其他方法可以调用窗口。
您可以将下面的代码用于Firefox和IE:
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
var confirmationMessage = 'Are you sure to leave the page?';
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
});
更新:
如果您的呼叫是异步的,则窗口将被关闭,您的呼叫不会开火。您必须在这样的事件中进行同步调用:
$.ajax({
type: 'POST',
async: false,
url: '/clientarea/utils/record-time',
data: 'teid=' + teid + '&t=' + t
});