Javascript 离开网站时弹出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11005887/
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-08-24 03:59:33  来源:igfitidea点击:

Popup when leaving website

javascriptpopupfunction-exit

提问by Daniil T.

I got a problem with JavaScript. I want a script that will pop-up on exit whole web-site a message with question and if visitor answers "NO" web page closes and if he answers "YES" he will be redirected to another page. I found a example at http://www.pgrs.net/2008/01/30/popup-when-leaving-website/but it seems that it doesnt work for me. I couldnt find any solution. Pleae check my code and tell me maybe i'm doing something wrong ? Here`s my source code.

我遇到了 JavaScript 问题。我想要一个脚本,它会在退出整个网站时弹出一条带有问题的消息,如果访问者回答“否”网页关闭,如果他回答“是”,他将被重定向到另一个页面。我在http://www.pgrs.net/2008/01/30/popup-when-leaving-website/找到了一个例子,但它似乎对我不起作用。我找不到任何解决方案。请检查我的代码并告诉我也许我做错了什么?这是我的源代码。

Maybe somebody will see a problem.

也许有人会看到问题。

 <!DOCTYPE html>
<html lang="lt">
<head>
    <meta charset="utf-8">
    <title>PUA.LT</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="description" content="">
    <meta name="author" content="Perfect WEB Solutions">
    <link rel="stylesheet" href="<?php echo base_url("additional/style.css") ?>">
    <script src='<?php echo base_url("additional/prototype.js")?>' type='text/javascript' ></script>
</head>
<body>
<script type="text/javascript">


Event.observe(document.body, 'click', function(event) {
  if (Event.element(event).tagName == 'A') {
    staying_in_site = true;
  }
});

window.onunload = popup;

function popup() {
  if(staying_in_site) {
    return;
  }
  alert('I see you are leaving the site');
}
</script>

</body>
</html>

回答by emphaticsunshine

Try this:

尝试这个:

window.onbeforeunload = popup;

function popup() {
  return 'I see you are leaving the site';
}