You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

两个Tampermonkey按键捕获脚本仅第二个生效,如何让两者同时工作?

问题原因与解决方案

问题根源

你遇到的核心问题是直接赋值window.onkeyup会覆盖之前的事件处理函数。两个脚本都用window.onkeyup = function(...)的方式绑定按键事件,后加载的脚本会完全替换掉前一个脚本的事件处理逻辑,所以只有Tampermonkey仪表板里排在后面的脚本能触发。

解决方案

改用addEventListener绑定keyup事件,这种方式可以同时注册多个事件处理函数,不会互相覆盖,能完美保持两个脚本的独立性。

修改后的脚本1

// ==UserScript==
// @name         Ctrl Y Function
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  testing key stroke function
// @author       You
// @match        https://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    window.addEventListener('keyup', function(e){
        if (e.key == "y" && e.ctrlKey){
            console.log("Ctrl + Y pressed!")
        }
    });
})();

修改后的脚本2

// ==UserScript==
// @name         Ctrl Q Function
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  testing key stroke function
// @author       You
// @match        https://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    window.addEventListener('keyup', function(e){
        if (e.key == "q" && e.ctrlKey){
            console.log("Ctrl + q pressed!")
        }
    });
})();

额外说明

  • 优先使用事件参数e而非全局event,前者在各类浏览器环境下兼容性更强、更规范。
  • 若后续需要移除事件监听,只需保存回调函数的引用,调用removeEventListener即可(当前场景无需此操作)。

内容的提问来源于stack exchange,提问作者PPL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:05:52