Skippy le Grand Gourou
Skippy le Grand Gourou

Reputation: 7724

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 :

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.

Upvotes: 0

Views: 801

Answers (1)

jmcgriz
jmcgriz

Reputation: 3368

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>

Upvotes: 2

Related Questions