简体   繁体   English

仅在浏览器关闭时通知用户

[英]Notify user on browser close only

I am trying to implement notifying when the user closes or reloades the page.Crrently i am using the following code我正在尝试在用户关闭或重新加载页面时实现通知。Crrently 我正在使用以下代码

function unloadPage(){
    return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;

This works fine.But the problem is this happens whenever a navigation takes place.That is either a page refresh or a form submission or a hyperlink click or whatever navigation takes place..I just want to work this code only for browser refreshing and closing.I knew about setting a flag and checking it.这工作正常。但问题是每当发生导航时就会发生这种情况。即页面刷新或表单提交或超链接点击或任何导航发生..我只想使用此代码仅用于浏览器刷新和关闭.我知道设置一个标志并检查它。 But i have to integrate this in a big application.So it will be difficult to add the code in every page.So is there an easy way.但是我必须将它集成到一个大的应用程序中。所以很难在每个页面中添加代码。所以有一个简单的方法。 Is there a way to catch the refresh or browser cosing so that can use it.有没有办法捕捉刷新或浏览器cosing,以便可以使用它。

Note that in your code, you're using onbeforeclose , but the event name is beforeunload , so property is onbeforeunload , not onbeforeclose .请注意,在您的代码中,您使用的是onbeforeclose ,但事件名称是beforeunload ,因此属性是onbeforeunload ,而不是onbeforeclose

I just want to work this code only for browser refreshing and closing.我只想将此代码仅用于浏览器刷新和关闭。 Is there a way to catch the refresh or browser cosing so that can use it.有没有办法捕捉刷新或浏览器cosing,以便可以使用它。

No. Instead, you'll have to capture each link and form submission and either set a flag telling your onbeforeunload handler not to return a string, or removing your onbeforeunload handler (probably the flag is cleaner).不。相反,您必须捕获每个链接和表单提交,并设置一个标志告诉您的onbeforeunload处理程序不要返回字符串,或者删除您的onbeforeunload处理程序(可能该标志更干净)。

For example:例如:

var warnBeforeClose = true;
function unloadPage(){
    if (warnBeforeClose) {
        return "Your changes will not be saved.";
    }
}
window.onbeforeunload = unloadPage;

// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
    // Don't warn
    warnBeforeClose = false;

    // ...but if we're still on the page a second later, set the flag again
    setTimeout(function() {
        warnBeforeClose = true;
    }, 1000);
}

Or without setTimeout (but still with a timeout):或者没有setTimeout (但仍然有超时):

var warningSuppressionTime = 0;
function unloadPage(){
    if (+new Date() - warningSuppressionTime > 1000) { // More than a second
        return "Your changes will not be saved.";
    }
}
window.onbeforeunload = unloadPage;

// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
    // Don't warn for the next second
    warningSuppressionTime = +new Date();
}

Update in 2017 : Also note that as of at least a couple of years ago, browsers don't show the message you return; 2017 年更新:另请注意,至少在几年前,浏览器不会显示您返回的消息; they just use the fact you returned something other than null as a flag to show their own, built-in message instead.他们只是使用您返回null以外的内容这一事实作为标志来显示他们自己的内置消息。

Check this link检查此链接

It gives you information on how to handle onbeforeunload event.它为您提供有关如何处理onbeforeunload事件的信息。

The idea is to have a global flag on the page.这个想法是在页面上有一个全局标志。 When any change is done to the fields, this flag is set to true.当对字段进行任何更改时,此标志设置为 true。 When clicked on save button, then this flag needs to be set to false.单击保存按钮时,此标志需要设置为 false。

In the onbeforeunload event, check whether the flag is true, then show the message accordingly.onbeforeunload事件中,检查标志是否为真,然后相应地显示消息。

var needToConfirm = true;

window.onbeforeunload = confirmExit;
function confirmExit()
{
    if (needToConfirm)
    {
        // check on the elements whether any change has been done on the fields.
        // If any change has been done, then set message here.
    }
}

function saveClicked()
{
    needToConfirm = false;
}

One of the simple solutions to your problem is to have a flag and then call your function only if the flag is valid.解决您的问题的一种简单方法是拥有一个标志,然后仅当该标志有效时才调用您的函数。 In this case , you can bind the anchor tags, F5 key and form submit button click to events that set the flag as false.在这种情况下,您可以将锚标记、F5 键和表单提交按钮单击绑定到将标志设置为 false 的事件。 So your alert bar will be visible only if the above cases don't happen :)因此,只有在上述情况不发生时,您的警报栏才会可见:)

Here's the script:这是脚本:

var validNavigation = false;

function endSession() {
  // Browser or broswer tab is closed
  alert("bye");
}

function wireUpEvents() {

  window.onbeforeunload = function() {
      if (!validNavigation) {
         endSession();
      }
  }

  // Attach the event keypress to exclude the F5 refresh
  $(document).bind('keypress', function(e) {
    if (e.keyCode == 116){
      validNavigation = true;
    }
  });

  // Attach the event click for all links in the page
  $("a").bind("click", function() {
    validNavigation = true;
  });

  // Attach the event submit for all forms in the page
  $("form").bind("submit", function() {
    validNavigation = true;
  });

  // Attach the event click for all inputs in the page
  $("input[type=submit]").bind("click", function() {
    validNavigation = true;
  });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
  wireUpEvents();  
});

DEMO演示

(Run or refresh the fiddle to see the alert onbeforeunload() event message and click on the link "kk" ,it wont show onbeforeunload() event message. Try it in your webpage) (运行或刷新 fiddle 以查看警报onbeforeunload()事件消息并单击链接“kk”,它不会显示onbeforeunload()事件消息。在您的网页中尝试)

I have a solution for you, you don have to add onclick event to each tags and all.我为您提供了一个解决方案,您不必为每个标签以及所有标签添加 onclick 事件。

Just add this to any where on your pages .只需将此添加到页面上的任何位置即可。

<input type="hidden" value="true" id="chk"/>

and add this code to your document head tag并将此代码添加到您的文档头标签

<script>
window.onbeforeunload = confirmExit;
function confirmExit()
{
   if(document.getElementById("chk").value=="true")
   {
      return "Your changes will not be saved.";
   }
}

document.onclick = myClickHandler;
function myClickHandler() {
      document.getElementById("chk").value="false";
    }
<script>

Hope this helps希望这可以帮助

Thank you谢谢

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

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