最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: Programmatically trigger onbeforeunloadonunload event - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

2 Answers 2

Reset to default 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'))

Either use

object.onunload=function(){myScript};

or the addEventListener() method:

object.addEventListener("unload", myScript);

to trigger the event use object.unload();

发布评论

评论列表(0)

  1. 暂无评论