问题
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