简体   繁体   English

onbeforeunload 在 codeigniter 中不起作用

[英]onbeforeunload not working in codeigniter

I have very simple code just to show a warning before page refreshed.我有非常简单的代码,只是为了在页面刷新之前显示警告。 The code uses Codeigniter as a framework (not sure if Codeigniter is related to the issue).该代码使用 Codeigniter 作为框架(不确定 Codeigniter 是否与该问题有关)。 I have a view file (test_v.php) with the following code:我有一个包含以下代码的视图文件(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>

Then I load this view file in a controller test.php $this->load->view('test_v');然后我将此视图文件加载到 controller test.php $this->load->view('test_v');

When I refresh the page, I expect to see a warning dialogue with the text 'Do you really want to perform the action?', but no warnings are shown at all.当我刷新页面时,我希望看到一个带有文本“您真的要执行该操作吗?”的警告对话框,但根本没有显示任何警告。 I have tested with IE, Firefox, Chrome.我已经用 IE、Firefox、Chrome 进行了测试。 None works.没有工作。 I have also tried adding the js code to the body label like this:我还尝试将 js 代码添加到正文 label 中,如下所示:

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

not working either.也不工作。 Could anyone help?有人可以帮忙吗? Thanks a lot!非常感谢!

I suggest using as an event listener like this:我建议像这样用作事件侦听器:

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 = '';
});

Per the MDN article :根据MDN 文章

Note: To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with.注意:为了防止不需要的弹出窗口,一些浏览器不显示在 beforeunload 事件处理程序中创建的提示,除非页面已经被交互。 Moreover, some don't display them at all.此外,有些根本不显示它们。

Might be the cause of your problem.可能是你的问题的原因。 I tested on a page and I didn't get the alert until interacted with the page.我在一个页面上进行了测试,直到与该页面交互后才收到警报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM