@peccul is peccu

(love peccu '(emacs lisp cat outdoor bicycle mac linux coffee))

ブラウザのタブを閉じようとした時にユーザーに確認を促す

beforeunload イベントをいじればよいようです。

f:id:peccu:20180221141754p:plain

サンプルコード

var modified = false;
window.addEventListener('beforeunload', function (e) {
  if(!modified){
    return;
  }
  var message = "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
  e.returnValue = message;
  return message;
});
document.querySelectorAll('input').forEach(function(input) {
  input.addEventListener('change', function (e) {
    window.modified = true;
  });
});

全てのinputタグが変更された時にフラグを立ててます。この辺りは初期状態の比較をするなどよしなに実装してください。 カスタムメッセージをサポートしているブラウザは少ないようですね。

参考