Javascript: Check if the user is navigating away with a form submit or a simple link click

試著忘記壹切 提交于 2019-12-24 04:53:35

问题


I need to do remind the users something when they are leaving the page, and that can be handled with the window.onUnload event. But I also need to check if the user is navigating away by submitting the form on the page, or by clicking the navigation links. I could use the form's onSubmit event to set a flag, and then check against that flag in the window.onUnload event, but I am not sure which one fires first.

any ideas ?


回答1:


You actually want window.onbeforeunload

window.onbeforeunload = function (e) {
  var e = e || window.event;

  // For IE and Firefox
  if (e) {
    e.returnValue = 'Are You Sure?';
  }

  // For Safari
  return 'Are You Sure?';
};



回答2:


It turns out that the form.onSubmit event fires first so i can use a flag. I have checked this in Firefox and Safari only.




回答3:


var isRefresh = true;
window.onunload = function () {
    alert('the page was ' + (isRefresh == false ? 'NOT ' : '') + 'refreshed');
}
$('a').live('click', function () { isRefresh = false; alert('a link was clicked'); });
$('form').bind('submit', function () { isRefresh = false; alert('form was submitted'); });

Based on How to capture the browser window close event?. I added the refresh logic.



来源:https://stackoverflow.com/questions/839780/javascript-check-if-the-user-is-navigating-away-with-a-form-submit-or-a-simple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!