离开页面 - 消息出现两次

时间:2015-11-20 12:00:30

标签: javascript

我已将此Javascript添加到我的网站,该网站检测用户何时离开页面,但我只想在导航器离线时显示警告并且我的某个元素包含单词"未保存":

window.thisPage = window.thisPage || {};
window.thisPage.closeEditorWarning = function (event) {
 if (navigator.onLine===false) {
  // See if any fields need saving...
  for (i = 1; i <= 500; i++) { 
   try {
    ToSave = document.getElementById("Q" + i).innerHTML;
    if (ToSave.indexOf("unsaved")!=-1) {
     return "You are currently offline and some of your responses are not yet saved.\r\n\r\nIf you want to save the changes you've made, choose to 'Stay on this Page' and then reconnect to the internet and any unsaved responses will save automatically.";
    }
   }
   catch(err) {  }
   // If got this far, nothing needs saving anyway...
  }
 }
 return undefined;
};

window.onbeforeunload = window.thisPage.closeEditorWarning;

代码工作正常,除了;如果消息弹出第一次,我选择&#34;留在此页面&#34;,然后尝试再次离开,第二次点击&# 34;离开这个页面&#34; - 而不是导航它再次显示消息,但我无法解决原因。

1 个答案:

答案 0 :(得分:0)

尝试从catch中返回true,这样卸载就会执行。您也可以从最后删除return undefined;

这对我有用,这是你之后的事吗?

这适用于Firefox。

小提琴: http://jsfiddle.net/518myq0j/3/(点击&#39;运行&#39;触发onbeforeunload

更新了JavaScript代码:

window.thisPage = window.thisPage || {};

window.thisPage.closeEditorWarning = function (event) {
    if (navigator.onLine === false) {
        // See if any fields need saving...
        for (i = 1; i <= 5; i++) {
            try {
                var ToSave = document.getElementById("Q" + i).innerHTML;
                if (ToSave.indexOf("unsaved") != -1) {
                    return "You are currently offline and some of your responses are not yet saved.\r\n\r\nIf you want to save the changes you've made, choose to 'Stay on this Page' and then reconnect to the internet and any unsaved responses will save automatically.";
                }
            } catch (err) {
                return true;
            }
        }
    }
};

window.onbeforeunload = window.thisPage.closeEditorWarning;