[英]JavaScript: How can I prompts a custom message box when they close broswer?
Problem:问题:
I am new in JavaScript.我是 JavaScript 的新手。 And I want to give a message like "you have down xxx works today,",
我想给一个消息,比如“你今天有 xxx 作品”,
when my users close broswer.当我的用户关闭浏览器时。 I've search google/stackoverflow and get some solutions in Prompt User before browser close?
我在浏览器关闭之前搜索了 google/stackoverflow 并在 Prompt User 中获得了一些解决方案?
BUT, when I try code as followd, it just shows the broswer's default message, not mine.但是,当我尝试如下代码时,它只显示浏览器的默认消息,而不是我的。 How can I solve it?
我该如何解决?
Code:代码:
function test(evt) {
var message = 'Did you remember to download your form?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
Are there some useful APIs or solutions for me?是否有一些对我有用的 API 或解决方案?
Edit (2021.9.22) I try the tips posted By @NiceBooks like编辑(2021.9.22)我尝试@NiceBooks 发布的提示,例如
window.addEventListener('beforeunload', function (e) {
window.alert("ready to exit");
window.confirm("just a test");
e.returnValue = '';
});
IE and FireFox prompt their default message. IE 和 FireFox 提示它们的默认消息。 If e.returnValue is not set, there is no prompt box when I click exit button.
如果没有设置e.returnValue,当我点击退出按钮时没有提示框。 beforeunload says:
beforeunload说:
'In some browsers, calls to window.alert(), window.confirm(), and window.prompt() may be ignored during this event. '在某些浏览器中,在此事件期间可能会忽略对 window.alert()、window.confirm() 和 window.prompt() 的调用。 See the HTML specification for more details.
有关详细信息,请参阅 HTML 规范。 '
'
Maybe it's the reason why I failed.也许这就是我失败的原因。 But is there really no solution?
但是真的没有解决办法吗?
You can try with the window.confirm(msg)
function.您可以尝试使用
window.confirm(msg)
function。
https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
Use it in conjunction with the beforeunload
event on the window
object:将它与
window
object 上的beforeunload
事件结合使用:
Try this, enter the following code inside the head
tag.试试这个,在
head
标签内输入以下代码。
<script>
const beforeUnloadListener = (event) => {
event.preventDefault();
return event.returnValue = "Are you sure you want to exit?";
};
//this piece of code will trigger a pupup message
addEventListener("beforeunload", beforeUnloadListener, {capture: true});
</script>
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.