关于窗口关闭事件的javascript [英] javascript on window close event

查看:74
本文介绍了关于窗口关闭事件的javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在检测我网站的用户是否关闭了窗口/标签或更改了网址。

I am currently detecting if a user of my site closes the window/tab or changes the url.

我正在使用以下代码,该代码完美无缺:

I am using the follwoing code, which works perfectly:

var validNavigation = false;

function endSession() {
  // Browser or broswer tab is closed
  // Do sth here ...
  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;
  });

}


$(document).ready(function() {
  wireUpEvents(); 
});

我的问题是我想将事件从警报更改为叠加层。我已经设置了隐藏的div叠加层,并将以上代码中的警报替换为:

My problem is i would like to change the event from an alert to a overlay. I have setup up a hidden div overlay and replaced the alert in the above code with:

$('.overlay').css('display','block');

这已经不再适用了,因为div中没有​​任何内容可以让用户留在页。 (用户无需点击提醒中的按钮)

This now no longer works, as there is nothing within the div to get the user to stay on the page. (the user doesn't have to click a button within an alert)

有关如何解决此问题的任何建议吗?

Any suggestions on how i can get around this?

干杯,Dan

推荐答案

窗口关闭事件将作为最后一个事件触发。因此,之后不会触发其他事件。

The window close event is fired as the very last event. Therefore no other events are fired after it.

您可以使用带有Jquery的beforeunload事件来显示屏幕上的叠加层。

You can use the beforeunload event with Jquery, to show the overlay on screen.

以下链接可能有所帮助:链接

The following link could help: link

这篇关于关于窗口关闭事件的javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆