简体   繁体   English

当用户离开我的网站时显示弹出窗口

[英]Show popup when user navigates away from my website

I want that user should be given a popup whenever he/she navigates away from my website(not just the webpage, the entire site). 我希望每当他/她离开我的网站(不仅是网页,还是整个网站)时,都应该给该用户一个弹出窗口。

I have implemented a method but it pop-up every time on navigating away from webpage. 我已经实现了一种方法,但是每次离开网页时都会弹出该方法。

window.onbeforeunload = function (evt) {


  var message = 'Are you sure you want to navigate away from myWEbSite?';
  if (typeof evt == 'undefined') {
    evt = window.event;

  }
  if (evt ) {
    evt.returnValue = message;
  }

  return message;

 }

You cannot get the new target url, since this is a protected information (see How can i get the destination url in javascript onbeforeunload event? ) 您无法获取新的目标URL,因为这是受保护的信息(请参阅如何在javascript onbeforeunload事件中获取目标URL?

So, you are not able to see, if the visitor leaves the website. 因此,您看不到访客是否离开了网站。

Alternative: you could listen all clicks on hyperlinks which refer to another webpage and implement a functionality which catches external links. 备选方案:您可以侦听对指向另一个网页的超链接的所有点击,并实现捕获外部链接的功能。

You can defile your own JQuery selectors, like this: 您可以删除自己的JQuery选择器,如下所示:

$.expr[':'].external = function(obj){
   return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$.expr[':'].internal = function(obj){
   return obj.hostname == location.hostname;
};

And then you can do the following: 然后,您可以执行以下操作:

$(function() {
    var unloadMessage = function() {
        return "Are you sure you want to navigate away from myWEbSite?";
    };

    $('a:internal').click(function() { 
        window.onbeforeunload = null;
    });
    $('form').submit(function() { 
        window.onbeforeunload = null;
    });

    $('a:external').click(function() { 
        window.onbeforeunload = unloadMessage;
    });

    window.onbeforeunload = unloadMessage;
});

In your specific case you just need to set window.onbeforeunload == null whenever a navigational link is clicked or an internal form is submitted. 在您的特定情况下,只要单击导航链接或提交内部表单,只需设置window.onbeforeunload == null

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

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