How to set the event to be triggered first?

狂风中的少年 提交于 2019-12-12 04:15:54

问题


I want to inject the javascript code to the website by Tampermonkey(a browser plugin which can inject userscript)

I want to inject:

function temp() {...}
window.addEventListener("beforeunload", temp);

the website may already has

window.onbeforeunload = function() {...}
window.addEventListener("beforeunload", otherFunction);

...etc, that is, the window object already has some events, and I even don't know what's their function name, and my "temp" function will be attached on window object last

but I want that temp function will be triggered first after the window is closed

Is that possible? thanks for help!!


回答1:


Add this jquery plugin:

(function ($) {
    $.fn.bindFirst = function(name, fn) {
       this.on(name, fn);
       this.each(function() {
          var handlers = $._data(this, 'events')[name.split('.')[0]];
          var handler = handlers.pop();
          handlers.splice(0, 0, handler);
       });
    };
})(jQuery);

and after that use like below:

window.bindFirst("beforeunload", temp);


来源:https://stackoverflow.com/questions/40821567/how-to-set-the-event-to-be-triggered-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!