Skippy le Grand Gourou Skippy le Grand Gourou - 6 months ago 14
Javascript Question

How can I trigger beforeunload warning when refreshing but not when submitting

Page 1 contains a dynamic form, page 2 is a review of submitted data. I have the following constraints :


  • no
    beforeunload
    warning when submitting page 1 ;

  • beforeunload
    warning when refreshing page 1 ;

  • no reloading of page 1 when issuing
    history.back()
    from page 2.



I tried to play with
window.onbeforeunload
and
$(window).unload()
(in page 1) but I can't seem to get the expected result.

Is this even possible, or are these constraints definitely contradictory (I mean, for a reasonable number of JS lines…) ?

Update :



I removed constraint 3 because according to some reading it deserves its own question.

Answer

You should be able to use something like this for parts 1 and 2, not sure what you mean with part 3 though

"use strict";
var isSubmit = false
document.querySelector('button').addEventListener('click', e => {
  isSubmit = true
  window.location.reload()
})

window.onbeforeunload = e => {
  if (!isSubmit) {
    return "Are you sure you want to leave?"
  }
}
<button>Submit</button>

Comments