重新加载浏览器后浏览器关闭时不显示警报,stackoverflow 网站也存在同样的问题

Alert not showing on browser close after doing reload of the browser, same issue is there in stackoverflow website also

我必须在浏览器关闭和刷新特定页面时显示警报。下面的代码适用于所有场景,但在下面的场景中失败。 1.首先,做刷新,然后警报会来要求重新加载,现在重新加载。 2.现在点击浏览器关闭按钮 问题:- 现在警报没有进入 chrome 和 Mozilla 浏览器,在 Edge 刷新时,警报多次出现我的代码是:-

window.onbeforeunload = (ev) => {
    let msg;
    debugger;
    if (sessionStorage.getItem('previousPage') === 'employee') {
       return 'Are you sure you want to navigate away?If you navigate away, your information will not be saved.'
        ev.preventDefault();
    }
    return msg;
};

请帮助我如何处理这种情况?

试试这个,与此非常相似::

window.onbeforeunload = function (ev) {
    window.onunload = function () {
        let msg;
        debugger;
        if (sessionStorage.getItem('previousPage') === 'employee') {
           return 'Are you sure you want to navigate away?If you navigate away, your information will not be saved.'
            ev.preventDefault();
        }
        return msg;
    }
};