onbeforeunload 在 codeigniter 中不起作用

问题描述 投票:0回答:2

我有非常简单的代码,只是在页面刷新之前显示警告。该代码使用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标签中,如下所示:

<body onbeforeunload=" return 'Do you really want to perform the action?'">

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

javascript php codeigniter onbeforeunload
2个回答
1
投票

我建议使用这样的事件监听器:

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

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


0
投票

我找到了解决方案。我正在注册一个与 beforeunload 事件关联的函数:

window.addEventListener("beforeunload", beforeUnloadHandler);

为了摆脱该消息,我必须调用此 JavaScript,以便在用户离开之前删除事件处理程序。原来第二个参数是必需的。

参见:https://www.w3schools.com/jsref/met_win_removeeventlistener.asp

window.removeEventListener("beforeunload", beforeUnloadHandler);

© www.soinside.com 2019 - 2024. All rights reserved.