7

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);

4

2 Answers 2

18
window.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')) 
Sign up to request clarification or add additional context in comments.

Comments

3

Either use

object.onunload=function(){myScript}; 

or the addEventListener() method:

object.addEventListener("unload", myScript); 

to trigger the event use object.unload();

2 Comments

Given the case that we have window.onbeforeunload=function(){return "you are leaving";} , if I call window.onbeforeunload, no alert box would pop up, but if I call window.location = 'http://someotherdomain.com' which will eventually trigger onbeforeunload, I see a pop up with the string "you are leaving". So is there a way to simulate leaving a page completely as it happens when we close a window?!(obviously I'm not looking for window.close())
I think the question is about programmatically triggering the browser confirmation that onbeforeunload creates. This answer doesn't really accomplish that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.