开发者

How to display onbeforeunload dialog when appropriate?

开发者 https://www.devze.com 2022-12-27 20:41 出处:网络
I\'ve got an editor in javascript on my webpage and I would like to ask user if he/she wants to leave the page even if there are unsaved changes.

I've got an editor in javascript on my webpage and I would like to ask user if he/she wants to leave the page even if there are unsaved changes.

I know I can add custom message to the "onbeforeunload dialog" this way:

window.onbeforeunload = function() {
  return 'You have unsaved changes!';
}

(Source) but I want to display the dialog only where there really开发者_JS百科 are some unsaved changes. How to do that?

Thanks!


You can do something like this:

var unsavedChanges = false;
window.onbeforeunload = function() {
  if (unsavedChanges) return 'You have unsaved changes!';
}

function makeSomeChange() {
  // do some changes....
  unsavedChanges = true;
}

You can make sure to change unsavedChanges in the 'change' event handlers.

0

精彩评论

暂无评论...
验证码 换一张
取 消