如何在使用 Javascript 离开页面之前调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28627111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a function before leaving page with Javascript
提问by PMay 1903
I would like to execute a function before leaving page without showing a confirmation popup with Javascriptonly. I've tried with the code below but it didn't work or with the onbeforeunloadbut it always shows the popup.
我想在离开页面之前执行一个函数而不显示仅使用Javascript的确认弹出窗口。我已经尝试过使用下面的代码,但它不起作用或使用 ,onbeforeunload但它总是显示弹出窗口。
var result = 'test';
if(window.onbeforeunload == true)
{
result = 'test1';
alertmess();
}
function alertmess() {
alert(result);
}
//window.onbeforeunload = function() {
// return result;
//}
回答by Jitendra Pancholi
You can always call your function before leaving the page.
您始终可以在离开页面之前调用您的函数。
function myfun(){
// Write your business logic here
console.log('hello');
}
onbeforeunload:
卸载前:
window.onbeforeunload = function(){
myfun();
return 'Are you sure you want to leave?';
};
Or with jQuery:
或者使用 jQuery:
$(window).bind('beforeunload', function(){
myfun();
return 'Are you sure you want to leave?';
});
This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.
这只会询问用户是否要离开页面,如果他们选择留在页面上,则无法重定向他们。如果他们选择离开,浏览器将转到他们告诉它去的地方。
You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):
您可以在页面卸载之前使用 onunload 执行操作,但您无法从那里重定向(Chrome 14+ 会阻止 onunload 内的警报):
window.onunload = function() {
myfun();
alert('Bye.');
}
Or with jQuery:
或者使用 jQuery:
$(window).unload(function(){
myfun();
alert('Bye.');
});
回答by Moob
Just call your function from within window.onbeforeunload. Note, some browsers restrict what you can do here (eg: no redirects or alerts). See: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunloadfor more info.
只需从内部调用您的函数window.onbeforeunload。请注意,某些浏览器会限制您在此处可以执行的操作(例如:没有重定向或警报)。请参阅:https: //developer.mozilla.org/en-US/docs/Web/Events/beforeunload了解更多信息。
I've also added the appropriate code for readers that dowant to show a confirmation dialog.
我还添加了相应的代码,读者也想显示确认对话框。
function doSomething(){
//do some stuff here. eg:
document.getElementById("test").innerHTML="Goodbye!";
}
function showADialog(e){
var confirmationMessage = 'Your message here';
//some of the older browsers require you to set the return value of the event
(e || window.event).returnValue = confirmationMessage; // Gecko and Trident
return confirmationMessage; // Gecko and WebKit
}
window.addEventListener("beforeunload", function (e) {
//To do something (Remember, redirects or alerts are blocked here by most browsers):
doSomething();
//To show a dialog (uncomment to test):
//return showADialog(e);
});
Just hit 'Run' to test: http://jsfiddle.net/2Lv4pa9p/1/
只需点击“运行”即可测试:http: //jsfiddle.net/2Lv4pa9p/1/
回答by Heemanshu Bhalla
Please try below simple code -
请尝试下面的简单代码 -
Jquery Code Example -
Jquery 代码示例 -
$(window).bind('beforeunload', function(){
Func_ToInsert_Record();
Alert('Thanks And Bye!');
});
Javascript Code Example -
Javascript 代码示例 -
// Anonymous function
window.onbeforeunload = function(event) {
var message = '';
if (window.event) {
console.log(window.event);
console.log(event.currentTarget.performance);
console.log(event.currentTarget.performance.navigation);
console.log(event.currentTarget.performance.navigation.type);
}
event = event || window.event;
event.preventDefault = true;
event.cancelBubble = true;
event.returnValue = message;
}
回答by Brandon Gano
If you want to prompt the user, return a string with the message. If you don't want to prompt the user, don't return anything.
如果要提示用户,请返回带有消息的字符串。如果您不想提示用户,请不要返回任何内容。
// Execute code, then prompt the user to stay
window.onbeforeunload = function () {
// This will happen before leaving the page
return 'Are you sure you want to leave?';
}
Or:
或者:
// Execute code, then leave
window.onbeforeunload = function () {
// This will happen before leaving the page
}
回答by JLRishe
What you're doing there is definitely not going to do it. Comparing window.onbeforeunloadto trueat some arbitrary time doesn't even make sense.
你在那里做的事情肯定不会去做。相比window.onbeforeunload于true在某个任意时间甚至没有任何意义。
What's with the commented out code at the end? If anything, you need to assign a function to onbeforeunload:
最后注释掉的代码是什么?如果有的话,您需要将一个函数分配给onbeforeunload:
var result = 'test';
window.onbeforeunload = function() {
result = 'test1';
alertmess();
}
function alertmess() {
alert(result);
}
However, the above only appears to work in IE. Please see @Bulk's comment and @Brandon Gano's answer.
但是,以上似乎只适用于 IE。请参阅@Bulk 的评论和@Brandon Gano 的回答。
回答by davejoem
The documentation here encourages listening to the onbeforeunloadevent and/or adding an event listener on window.
此处的文档鼓励侦听onbeforeunload事件和/或在窗口上添加事件侦听器。
window.addEventListener('onbeforeunload', function(e) {}, false);
You can also just populate the .onunloador .onbeforeunloadproperties of windowwith a functionor a function reference.
您也可以使用函数或函数引用填充.onunload或.onbeforeunload属性。window
Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.
虽然跨浏览器的行为没有标准化,但该函数可能会返回一个值,浏览器在确认是否离开页面时将显示该值。
回答by Gabriel Glauber
I simple put this code and works preety well
我简单地放了这段代码并且工作得很好
window.onbeforeunload = function(event) {
$('element').show();
return;
};
回答by VasaraBharat
This is an example of how you could handle the navigate away. Notice how a div appears a little before the navigation occurs.
这是您如何处理导航离开的示例。注意在导航发生之前 div 是如何出现的。
window.onbeforeunload = function ()
{
$("#oi").append($('<div>This is the child DIV</div>'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="theMainDiv">
The Main Div will receive another div before leaving the page
</div>
<button onclick="window.location.href='pageAway'">Navigate Away</button>

