两个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
相关产品推荐
相关产品推荐

