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

176
Views
Warn web user if the back button was pressed using javascript

Hi I tried to use the following javascript to warn users.

 window.onbeforeunload = function() {
       return "Are you sure you wish to leave?";
    };

But I need to make sure that the back button is pressed it seems to call this when you change the url.

Thanks

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

you can play with popstate event browser fired when browser history change

window.addEventListener('popstate', function(event) {
  alert('you click on back or forward button');
}

The popstate event is fired when the current history changes :

  • when buttons back/forward are click by user
  • when methods history.back(), history.forward(), history.go() are called.
about 4 years ago · Juan Pablo Isaza Report

0

Try looking through these answers here.

So, in short, and for people that aren't necessarily using an in-page back button or an array to store the history:

document.onmouseover = function() {
    //User's mouse is inside the page.
    window.innerDocClick = true;
}

document.onmouseleave = function() {
    //User's mouse has left the page.
    window.innerDocClick = false;
}

window.onhashchange = function() {
    if (window.innerDocClick) {
        //Your own in-page mechanism triggered the hash change
    } else {
        //Browser back button was clicked
    }
}

And there you have it. a simple, three-part way to detect back button usage vs in-page elements with regards to hash navigation.

Your alert would go into the else section of the window.onhashchange handler.

about 4 years ago · Juan Pablo Isaza 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!