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

237
Views
How to call a function before leaving page via HTML <a> target Attribute with Javascript

I have an HTML tag with a target attribute. The issue is that I want to prevent the user leaving my site this way without saving his changes.

I tried

window.onbeforeunload = function(){
  myfun();
  return 'Are you sure you want to leave?';
};

Also changed my code to:

window.addEventListener('onbeforeunload', (e) => {
      e.preventDefault();
      console.log('Inside event')
    })

But that didn't do it...

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

0

The return 'string' method does not work reliably everywhere. Most, if not all Web browsers won't show a custom message. And you also need to call preventDefault on the event:

window.onbeforeunload = (event) => {
  myfun();
  event.preventDefault();
  return 'Are you sure you want to leave?';
};

EDIT This will not work using alert, confirm or prompt because it will override the browser's default message before displayed. You can do anything else though:

window.onbeforeunload = function(e){
  console.log('Leaving...');
  e.preventDefault();
};
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!