1

I recently added a JavaScript dialog into my page, which will let the user confirm if they really want to leave the page. However, I also have buttons navigating to other pages on my page, and I don't want the leaving site confirm dialog to show up when users click these buttons.

I haven't really found out a way on how to do this, partly because I'm new to HTML and JavaScript.

Below is my code I'm using for the confirm dialog, which I also got from here on Stack Overflow.

window.onbeforeunload = function (e) {
    e = e || window.event;

    if (e) {     // For IE and Firefox prior to version 4
        e.returnValue = 'Any string';
    }

    return 'Any string';     // For Safari
};
Francis
  • 15
  • 4
  • Possible duplicate of [Disable Browser onUnload on certain links?](https://stackoverflow.com/questions/16116230/disable-browser-onunload-on-certain-links), [javascript onbeforeunload disable for links](https://stackoverflow.com/questions/18932464/javascript-onbeforeunload-disable-for-links) – Tyler Roper Jul 21 '19 at 02:46

1 Answers1

0

You can use a global variable to control the way to navigate.

Here is an example, I use a variable called needConfirm to handle the webpage will show confirm message or not.

var needConfirm = true;
window.onbeforeunload = function (e) {
  if (!needConfirm) {
    return; // do nothing, just redirect...
  }

  e = e || window.event;

  if (e) {     // For IE and Firefox prior to version 4
    e.returnValue = 'Any string';
  }

  return 'Any string';     // For Safari
};

// function to change needConfirm value to `false`
function disableConfirm() {
  needConfirm = false;
}

Call disableConfirm() onClick for button and links which you want to allow. E.g.

<a href="/other_page_url" onClick="disableConfirm()">Redirect without confirmation...</a>
hoangdv
  • 15,138
  • 4
  • 27
  • 48