4

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.

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>
Daniil T.
  • 1,145
  • 2
  • 13
  • 33
  • possible duplicate of [Javascript - Confirmation when leaving page](http://stackoverflow.com/questions/3156052/javascript-confirmation-when-leaving-page) – TheHippo Jun 12 '12 at 22:42
  • and this one too [Best way to detect when user leaves a web page](http://stackoverflow.com/questions/147636/best-way-to-detect-when-user-leaves-a-web-page) – Brad Jun 12 '12 at 22:47

1 Answers1

12

Try this:

window.onbeforeunload = popup;

function popup() {
  return 'I see you are leaving the site';
}
emphaticsunshine
  • 3,725
  • 5
  • 32
  • 42
  • 1
    This answer is correct. You can't have any alerts, standard popups, confirm messages happen when a page unloads. The return message is a confirm, but its as far as you can go. Great stuff :) – matsko Jun 12 '12 at 23:00
  • Your script will activate popup if even i click on internal links such as menu links. I need only on whole web exit. Also i`am using Prototype.js framework – Daniil T. Jun 13 '12 at 11:44
  • You have to nullify onbeforeunload. If it is clicked within a website, you have to do something like this: window.onbeforeunload = null; – emphaticsunshine Jun 13 '12 at 12:19
  • 2
    this is not working in my chrome browser , is this browser dependent? – Gomzy Jun 11 '19 at 04:43
  • This does not work – Kornel Dec 22 '22 at 19:42