如何在没有弹出消息的情况下使用 onbeforeunload 事件处理程序?

How to use onbeforeunload event handler without the pop up message?

您好,我正在尝试使用 onbeforeunload 事件来记录页面的一些最终日志 (我不能在访问中途这样做,因为我必须在用户离开之前获得正确的日志。)

function handleBeforeUnload(evt) {
    evt.preventDefault();
    evt.returnValue = '';

    // make some log
    logSomeFinalizedInfo();

    return null;
}

然而,在Androidphone,这会弹出一个消息“你确定要离开吗”,这不是预期的,我如何在没有这个消息的情况下使用这个事件处理程序弹出?

谢谢!

请考虑使用专门用于此目的的 Beacon API
此处有更多信息 - https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API

Not only do these techniques represent poor coding patterns, some of them are unreliable and result in the perception of poor page load performance for the next navigation. The Beacon API provides a standard way to address these issues.

终于找到了解决办法,就是在使用后移除handler(removeEventListener):

function handleBeforeUnload(evt) {
    evt.preventDefault();
    evt.returnValue = '';

    // make some log
    logSomeFinalizedInfo();

    removeEventListener('beforeunload', handleBeforeUnload);
}