Alert user before leaving page to prevent unsaved data on iOS browsers (Safari/Chrome)

227 views Asked by At

I'm developing a website which allow users to fill a form. I tried to show an alert to prevent users from accidentally leaving the page with unsaved data, by creating handlers for those events: beforeunload, pagehide, but none of them work on Safari/Chrome on iOS devices (iPhone, iPad).

How can I show an alert for the case described above (for browsers on iOS devices)? Thank you!

The code I tried but not working:

window.onbeforeunload = event => {
  event.preventDefault();
  event.returnValue = true;
  return true;
};

window.addEventListener('beforeunload', event => {
  event.preventDefault();
  event.returnValue = true;
});

window.addEventListener('pagehide', event => {
  event.preventDefault();
  event.stopPropagation();
});

None of them showing any alert when user leave the page (even if user has interacted with the page, e.g. entered some inputs).

0

There are 0 answers