Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Notification when user try to close browser or tab

My script

<script type="text/javascript">
      var hook = true;
      window.onbeforeunload = function() {
        if (hook) {
          return "Do you sure what to leave"
        }
      }
      function unhook() {
        hook=false;
      }
    </script> 

This code blocks user when

  • User try to close browser or tab
  • When user clicked external link
  • When user clicked internal link
  • When user refresh the page

I only want to block user when they try to close browser or tab.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

This is normally used to prevent users lost their drafts from unexpected page leave actions, so normally we will only set this up when user typed something in a input/textarea etc..., and it's predictable user action (cause we can detect if user entered anything or not).

But, you want to block user only when they're trying to close browser or tab, this is not a predictable action, and it cannot always be detectable (such like closing browser).

So, if you want to do so, I think you need to attach listeners to any other acceptable page leave actions (like those you mentioned), and cancel blocking by returning null/false in onbeforeunload.

For example, this accept link redirects:

window.onbeforeunload = () => true;

document
  .querySelectorAll("a")
  .forEach((element) =>
    element.addEventListener(
      "click",
      () => (window.onbeforeunload = null)
    )
  );

I don't know how to detect page reload, maybe by detecting F5 button is pressed or not? but this can't know if user manually click refresh button on browser.

Btw, you should really reconsider that why you would like to do that, cause if it's not for prevent users from lose their drafts, then I think it's not a user-friendly action.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!