javascript 如何检测用户退出页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24016658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:59:51  来源:igfitidea点击:

How can I detect a user about the exit the page?

javascriptjqueryhtmlback

提问by Tzach

I would like to detect when a user is about to exit the page, before they click the back button, and do something - for example display a popup. I do not want to prevent the user from leaving the page, but only to grab their attention again.

我想检测用户何时即将退出页面,然后再单击后退按钮并执行某些操作 - 例如显示弹出窗口。我不想阻止用户离开页面,而只是为了再次吸引他们的注意力。

This is already done by Optin Monster, but I want to implement it myself.

这已经由Optin Monster完成,但我想自己实现它。

Where to start?

从哪儿开始?

Edit: beforeunloadis fired afterthe user clicked the back or x button. I would like to catch his exit intent, for example when the mouse is moving towards the back button, but before it was clicked.

编辑: 在用户单击后退或 x 按钮beforeunload触发。我想抓住他的退出意图,例如当鼠标移向后退按钮时,但在点击之前。

回答by Hristo Georgiev

Here's how you can do it:

您可以这样做:

$(document).on('mouseleave', leaveFromTop);

function leaveFromTop(e){
    if( e.clientY < 0 ) // less than 60px is close enough to the top
      alert('y u leave from the top?');
}

I hope this is what you are looking for. Good luck!

我希望这就是你要找的。祝你好运!

回答by A. Wolff

Ouibouncedoes this. There is a live demo here.

Ouibounce 就是这样做的。这里有一个现场演示

npm install ouibounce

Then:

然后:

var ouibounce = require('ouibounce');
var modal = document.getElementById('ouibounce-modal')
ouibounce(modal);

回答by Ernesto Hegi

The problem I find with these techniques (like the one implemented on Ouibounce or the one proposed by Hristo Georgiev) is they also detect when the mouse enters the window if the cursor is outside the page before page load. It's not a big deal, but it might bring an unwanted behavior. An extra tweak must be done for this solution to work fine. One thing that comes to my mind right know would be to use a flag to check the mouse logic.

我发现这些技术的问题(如在 Ouibounce 上实现的技术或 Hristo Georgiev 提出的技术)是如果在页面加载之前光标位于页面之外,它们还会检测鼠标何时进入窗口。这没什么大不了的,但它可能会带来不需要的行为。必须进行额外的调整才能使此解决方案正常工作。我想到的一件事是使用标志来检查鼠标逻辑。