简体   繁体   English

离开页面-消息出现两次

[英]Leaving a page - message appears twice

I've added this Javascript to my website which detects when the user navigates away from the page, but I only want a warning to appear if the navigator is offline AND one of my elements contains the word "unsaved": 我已将此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;

The code works fine except; 该代码工作正常,除了; if the message pops up the first time and I choose "Stay on this page", then try to navigate away again and the second time click "Leave this page" - rather than navigating away it displays the message again but I can't work out why. 如果消息是第一次弹出,而我选择“停留在此页面上”,则尝试再次导航,然后第二次单击“离开此页面”-而不是导航离开,它会再次显示该消息,但我不能工作搞清楚为什么。

Try returning true from your catch, so the unload will execute. 尝试从捕获中返回true ,以便执行卸载。 You can also remove the return undefined; 您也可以删除return undefined;return undefined; from the end. 从头开始。

This works for me, is this what you're after? 这对我有用,这是您的追求吗?

This works for me in Firefox. 这对我在Firefox中有效。

Fiddle: http://jsfiddle.net/518myq0j/3/ (clicking 'Run' triggers the onbeforeunload ) 小提琴: http : //jsfiddle.net/518myq0j/3/ (单击“运行”将触发onbeforeunload

Updated JavaScript code: 更新的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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM