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

时间:2015-02-20 10:47:51

标签: javascript

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

var result = 'test';

if(window.onbeforeunload == true)
{
    result = 'test1';
    alertmess();
}

function alertmess() {
    alert(result);
}

//window.onbeforeunload = function() { 
//  return result; 
//}

8 个答案:

答案 0 :(得分:37)

您可以在离开页面之前随时调用您的功能。

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

onbeforeunload:

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

答案 1 :(得分:2)

只需在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/

答案 2 :(得分:1)

请尝试以下简单代码 -

Jquery代码示例 -

$(window).bind('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;
}

答案 3 :(得分:0)

你在做什么绝对不会这样做。在某个任意时间将window.onbeforeunloadtrue进行比较甚至没有意义。

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

var result = 'test';

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

function alertmess() {
  alert(result);
}

但是,以上只能在IE中使用。请参阅@ Bulk的评论和@Brandon Gano的回答。

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

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

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

您还可以使用功能功能参考填充.onunload的{​​{1}}或.onbeforeunload属性。< / p>

虽然浏览器的行为没有标准化,但该功能可能会返回一个值,浏览器在确认是否离开页面时会显示该值。

答案 6 :(得分:-1)

这是一个如何处理导航的示例。注意在导航发生之前div是如何出现的。

&#13;
&#13;
window.onbeforeunload = function () 
{
   $("#oi").append($('<div>This is the child DIV</div>'));
 
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 7 :(得分:-1)

我简单地把这个代码放在一边,并且工作得很好

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