How can I programmatically trigger onbeforeunload and onunload events?(No jquery please). I've tried:
var event = new Event('onbeforeunload');
event.initEvent("onbeforeunload", true, true);
window.document.dispatchEvent(event);
How can I programmatically trigger onbeforeunload and onunload events?(No jquery please). I've tried:
var event = new Event('onbeforeunload');
event.initEvent("onbeforeunload", true, true);
window.document.dispatchEvent(event);
Share
Improve this question
edited Jul 18, 2015 at 20:48
Alex
asked Jul 18, 2015 at 20:41
AlexAlex
1,9946 gold badges28 silver badges49 bronze badges
4
- Please show your code. – Lance Commented Jul 18, 2015 at 20:44
- 1 possible duplicate of stackoverflow.com/questions/3490331/… – Tushar Gupta Commented Jul 18, 2015 at 20:50
- 2 Possible duplicate of Is it possible to trigger the onbeforeunload event programmatically? – Brilliand Commented Aug 10, 2018 at 23:07
- Note: The above mentioned articles refer to jQuery based solutions. – Thomas Williams Commented Nov 8, 2019 at 11:02
2 Answers
Reset to default 18window.dispatchEvent(new Event('beforeunload'))
I think this would be the best way in 2020. In case anyone finds this.
window.addEventListener('beforeunload',()=>{console.log("beforeunload triggered")})
window.dispatchEvent(new Event('beforeunload'))
Either use
object.onunload=function(){myScript};
or the addEventListener() method:
object.addEventListener("unload", myScript);
to trigger the event use object.unload();