首页 > 解决方案 > 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?'">

也不工作。有人可以帮忙吗?非常感谢!

标签: javascriptphpcodeigniteronbeforeunload

解决方案


我建议像这样用作事件侦听器:

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 事件处理程序中创建的提示,除非页面已经被交互过。此外,有些根本不显示它们。

可能是你的问题的原因。我在一个页面上进行了测试,直到与该页面交互后才收到警报。


推荐阅读