javascript - onbeforeunload 在 codeigniter 中不起作用
问题描述
我有非常简单的代码,只是为了在页面刷新之前显示警告。该代码使用 Codeigniter 作为框架(不确定 Codeigniter 是否与问题有关)。我有一个包含以下代码的视图文件(test_v.php):
<?php ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body >
<p>Test onbeforeunload</p>
<script type="text/javascript">
window.onbeforeunload = function () {
return 'Do you really want to perform the action?';
}
</script>
</body>
</html>
然后我在控制器中加载这个视图文件 test.php $this->load->view('test_v');
当我刷新页面时,我希望看到一个带有文本“您真的要执行该操作吗?”的警告对话框,但根本没有显示任何警告。我已经用 IE、Firefox、Chrome 进行了测试。没有工作。我还尝试将 js 代码添加到正文标签,如下所示:
<body onbeforeunload=" return 'Do you really want to perform the action?'">
也不工作。有人可以帮忙吗?非常感谢!
解决方案
我建议像这样用作事件侦听器:
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
// Chrome requires returnValue to be set
e.returnValue = '';
});
根据MDN 文章:
注意:为了防止不需要的弹出窗口,一些浏览器不会显示在 beforeunload 事件处理程序中创建的提示,除非页面已经被交互过。此外,有些根本不显示它们。
可能是你的问题的原因。我在一个页面上进行了测试,直到与该页面交互后才收到警报。
推荐阅读
- azure - Azure 数据工厂 - 超出最大调用堆栈大小
- dart - Flutter:如何使用 JSON 加载所有分页数据
- fork - systemd 如何使用 Type=fork 跟踪 fork 进程
- sql - 结合 LEFT JOINS 和 INNER JOINS 的 MS ACCESS SQL 问题
- angular - 使用 *ngFor 创建多个复选框
- r - 在 Stan 中开发非线性增长曲线模型的分层版本
- android - 使用 Android Studio 3.2 Canary 17 时出现 kotlin-android 错误
- node.js - npm install 不安装我的依赖项
- reactjs - 拥有 .bind() 的目的
- actionscript-3 - 在 AS3 中将影片剪辑拖到另一个影片剪辑上时使用 mouse_over