简体   繁体   中英

Making the leaving site confirm dialog not showing up when a button on the page is clicked

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
};

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. Eg

<a href="/other_page_url" onClick="disableConfirm()">Redirect without confirmation...</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM