如何在使用 Javascript 离开页面之前调用函数

How to call a function before leaving page with Javascript

本文关键字:调用 函数 离开 Javascript      更新时间:2024-02-29

我想在离开页面之前执行一个函数,而不显示仅使用 Javascript 的确认弹出窗口。我尝试使用下面的代码,但它不起作用或onbeforeunload但它总是显示弹出窗口。

var result = 'test';
if(window.onbeforeunload == true)
{
    result = 'test1';
    alertmess();
}
function alertmess() {
    alert(result);
}
//window.onbeforeunload = function() { 
//  return result; 
//}

您始终可以在离开页面之前调用函数。

function myfun(){
     // Write your business logic here
     console.log('hello');
}

在卸载之前:

window.onbeforeunload = function(){
  myfun();
  return 'Are you sure you want to leave?';
};

或者使用 jQuery:

$(window).bind('beforeunload', function(){
  myfun();
  return 'Are you sure you want to leave?';
});

这只会询问用户是否要离开页面,如果他们选择留在页面上,您将无法重定向他们。如果他们选择离开,浏览器将转到他们告诉它去的地方。

您可以在卸载页面之前使用 onunload 来执行操作,但不能从那里重定向(Chrome 14+ 会在 onunload 中阻止警报(:

window.onunload = function() {
    myfun();
    alert('Bye.');
}

或者使用 jQuery:

$(window).unload(function(){
  myfun();
  alert('Bye.');
});

只需从 window.onbeforeunload 中调用您的函数即可。请注意,某些浏览器会限制您可以在此处执行的操作(例如:没有重定向或警报(。有关详细信息,请参阅:https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload。

我还为想要显示确认对话框的读者添加了适当的代码

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

只需点击"运行"即可测试:http://jsfiddle.net/2Lv4pa9p/1/

请尝试以下简单代码 -

J查询代码示例 -

$(window).on('beforeunload', function(){
  Func_ToInsert_Record();
  alert('Thanks And Bye!');
});

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;
}

如果要提示用户,请返回包含消息的字符串。如果不想提示用户,请不要返回任何内容。

// 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?';
}

或:

// Execute code, then leave
window.onbeforeunload = function () {
  // This will happen before leaving the page
}

此处的文档鼓励侦听 onbeforeunload 事件和/或在窗口上添加事件侦听器。

window.addEventListener('onbeforeunload', function(e) {}, false);

也可以只使用函数或函数引用填充window.onunload.onbeforeunload属性

尽管跨浏览器的行为没有标准化,但该函数可能会返回一个值,浏览器在确认是否离开页面时将显示该值。

你在那里做的事情绝对不会做。在某个任意时间将window.onbeforeunloadtrue进行比较甚至没有意义。

最后注释掉的代码是怎么回事?如果有的话,你需要为onbeforeunload分配一个函数:

var result = 'test';
window.onbeforeunload = function() {
  result = 'test1';
  alertmess();
}
function alertmess() {
  alert(result);
}

但是,上述内容似乎仅适用于IE。请参阅@Bulk的评论和@Brandon Gano的回答。

'beforerunload' 不再起作用,你可以改用 'unload' 事件,即使不推荐它,或者 'visibilitychange' 或 'hidepage' 事件。

window.addEventListener("visibilitychange", function(event) {
   
    console.log("hey");   
});

这是如何处理导航的示例。请注意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>

我简单地放置了这段代码并且工作得很好

window.onbeforeunload = function(event) {
    $('element').show();
    return;
};