简体   繁体   English

用户离开或刷新页面时如何自定义对话框消息

[英]How can I customize the dialog box message when user leaving or refreshing the for page

I used beforeUnload event listener, but I couldn't get the message I want to be displayed on dialog-box.我使用了beforeUnload事件侦听器,但是我无法获得想要在对话框中显示的消息。
Here is my code:这是我的代码:

//code//[enter image description here][1]
window.addEventListener('beforeunload', function(event) {
  
  var message = ' customized message ';
  (window.event).returnValue = message;
  return message;
});

Note;笔记; can I use preventDefault() method instead return value?我可以使用preventDefault()方法而不是返回值吗? I tried with我试过

{event.preventDefault();
   return message;}

But this isn't working.但这不起作用。

What you're doing is not wrong, the problem is that not all browsers display the returned message.您所做的没有错,问题是并非所有浏览器都显示返回的消息。 Prevent default won't help you.防止默认不会帮助你。

Quoting Mozilla :引用Mozilla

Some browsers display the returned string in the dialog box, but others display their own message.一些浏览器在对话框中显示返回的字符串,但其他浏览器显示自己的消息。 If no value is provided, the event is processed silently.如果未提供任何值,则将静默处理该事件。

For better cross-browser results, keep appending the message to the event handler and don't just return the message.为了获得更好的跨浏览器结果,请继续将消息附加到事件处理程序,不要只返回消息。

window.addEventListener('beforeunload', function (event) {
  var message = ' customized message ';

  event.returnValue = message; // Gecko, Trident, Chrome 34+
  return message;              // Gecko, WebKit, Chrome <34
});

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

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