javascript - 离开站点 javascript 事件 - onbeforeunload - 刷新页面/内部超链接

标签 javascript

我正在尝试如下所示的 onbeforeunload 事件,当我关闭浏览器时它工作正常

    <script type="text/javascript" language="javascript">
    window.onbeforeunload = LeavingSiteHandler;
    function LeavingSiteHandler(e) {
        if (!e) 
            e = window.event;
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
        }
    }
</script>

但是,当我按 F5 刷新页面或单击内部链接时,将触发此事件。是否可以检查点击的超链接是否为内部链接?如果我按 F5,是否可以停止此弹出消息? 非常感谢!

最佳答案

您可以为页面中的链接编写一个 onclick 处理程序,在其中删除 window.onbeforeunload 处理程序。

但是您无法区分页面刷新和关闭选项卡/窗口。

关于javascript - 离开站点 javascript 事件 - onbeforeunload - 刷新页面/内部超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5501163/

相关文章:

.net javascript 母版页乱码元素名称有解决办法吗?

javascript - 将 jQuery 注入(inject) TypeScript 函数

javascript - jquery 数字验证不起作用

java - 浏览器不生成文件下载对话框

javascript - 刷新页面不会应用 Angular 中的更改

javascript - AMCharts 类别标题位置

javascript - 理解 javascript 闭包

javascript - 如何使用 Javascript 同时更改同一页面中的两个背景图像?

javascript - react .js : Is it possible to namespace child components while still using JSX to refer to them?

javascript - jVectorMap 改变 SVG 描边颜色