0

What I am trying to achieve is that if user clicks on close button a function Exit is triggered which displays a form before user leaves the website.But my form is not getting displayed

Javascript

<script type="text/javascript">

  window.onbeforeunload = Exit;

      function Exit()
      {
          setTimeout(function() {
            setTimeout(function() {
             document.getElementById('form').style.display="block";
               window.location.href="register.html";
            }, 1000);
        },1);
        return "Message";
      }
    </script>

Html code

<div class="container">

  <form role="form" id="form" method="post" action="register.php" style="display:none">
    <div class="form-group">
      <label for="username">Name:</label>
      <input type="text" name="username" class="form-control" id="username" placeholder="Enter name">
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" name="email" class="form-control" id="email" placeholder="Enter email">
    </div>
    <div class="form-group">
      <label for="phone">Phone Number:</label>
      <input type="number" name="phone" class="form-control" id="phone" placeholder="Enter phonenumber">
    </div>
  <div class="form-group">
      <label for="reason">Reason to leave:</label>
      <textarea class="form-control" name="reason" rows="5" id="comment"></textarea>
    </div>
    <button type="submit" name="submit" class="btn btn-default">Submit</button>
  </form>
</div>
Ahmed Shamel
  • 1,982
  • 3
  • 24
  • 58
art
  • 226
  • 3
  • 11
  • 30
  • 2
    Possible duplicate of [Getting onBeforeUnload to work with a setTimeout](http://stackoverflow.com/questions/12571705/getting-onbeforeunload-to-work-with-a-settimeout) – Blue Aug 13 '16 at 11:55
  • I don't think that overwriting the value of window.location.href is allowed inside a window.onbeforeunload. Otherwise the user could never close the tab. – Walle Cyril Aug 13 '16 at 14:48
  • 2
    You are trying to block user interaction, with a 1 second delay, for marketing purposes. When encountered, I won't be coming back, and I'll probably start probing your website's security for fun. It's out of scope for this website, but I highly suggest looking into other solutions. This is probably the reason that browsers don't allow stuff like this to happen. Looking at the official specs (https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload) it seems u can do some stuff on the background (cleaning session data?) and/or let the browser handle a pop-up message. – vandijkstef Aug 13 '16 at 15:03

0 Answers0