【问题标题】:How to set the event to be triggered first?如何设置事件先触发?
【发布时间】:2016-11-26 18:19:42
【问题描述】:

我想通过 Tampermonkey(可以注入用户脚本的浏览器插件)将 javascript 代码注入网站

我要注入:

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

网站可能已经有

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

...等等,就是window对象已经有了一些事件,我什至不知道它们的函数名是什么,我的“temp”函数最后会附加到window对象上

但我希望在关闭窗口后首先触发临时功能

这可能吗?感谢您的帮助!

【问题讨论】:

    标签: javascript html event-handling tampermonkey dom-events


    【解决方案1】:

    添加这个 jquery 插件:

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

    然后使用如下:

    window.bindFirst("beforeunload", temp);
    

    【讨论】:

    • 谢谢...但是你可以提供纯 javascript 版本吗?我会很感激的
    • 很抱歉,但我认为这不是答案,因为原始网站的事件是使用纯 javascript 和 jquery 无法收集它甚至更改执行顺序
    猜你喜欢
    • 2011-12-26
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多