Tampermonkey全局函数仅首次可在控制台调用,办公PC求助
解决Tampermonkey全局函数仅能在控制台首次调用的问题
针对办公PC上Tampermonkey添加的全局函数后续无法在控制台调用的问题,提供以下针对性解决方案:
1. 用DOM脚本注入强制绑定到页面上下文
如果直接挂载window或unsafeWindow无效,说明办公环境的隔离机制更严格,可以通过注入原生脚本标签的方式,将函数直接写入页面的全局上下文:
// ==UserScript== // @name Global Function Fix // @namespace http://tampermonkey.net/ // @version 0.1 // @description Make global functions accessible in console permanently // @match *://your-target-site.com/* // @grant none // ==/UserScript== (function() { 'use strict'; // 创建脚本标签,将函数定义直接注入页面 const script = document.createElement('script'); script.textContent = ` window.myFunctions = window.myFunctions || {}; window.myFunctions.onKeyDown = function(event) { const keyName = event.key; if (keyName === "Alt") return; if (event.altKey) { switch (keyName) { case 'a': console.log("alt a pressed"); break; case 's': console.log("alt s pressed"); break; } } }; document.addEventListener("keydown", window.myFunctions.onKeyDown, false); `; document.head.appendChild(script); })();
这种方式绕过Tampermonkey的沙箱,直接在页面原生上下文定义函数,完全不受沙箱隔离影响。
2. 检查并绕过页面CSP限制
办公场景的网站可能设置了严格的内容安全策略(CSP),阻止了脚本注入或window对象修改。可以:
- 打开控制台的「安全」标签,查看是否有CSP相关报错
- 如果是CSP限制,在Tampermonkey脚本头部添加
@grant unsafeWindow和@inject-into content,强制脚本注入到页面内容上下文:
// ==UserScript== // ... 其他配置 ... // @grant unsafeWindow // @inject-into content // ==/UserScript==
3. 锁定全局对象防止被覆盖
部分页面脚本会重置或覆盖window上的自定义属性,可通过Object.defineProperty将全局函数设为不可修改:
(function() { 'use strict'; const myFunctions = { onKeyDown: function(event) { const keyName = event.key; if (keyName === "Alt") return; if (event.altKey) { switch (keyName) { case 'a': console.log("alt a pressed"); break; case 's': console.log("alt s pressed"); break; } } } }; // 锁定window.myFunctions,防止被覆盖 Object.defineProperty(window, 'myFunctions', { value: myFunctions, writable: false, enumerable: true, configurable: false }); document.addEventListener("keydown", myFunctions.onKeyDown, false); })();
4. 调整脚本执行时机
将脚本执行时机设为document-start,确保在页面脚本加载前就完成全局函数的绑定,避免被后续页面代码覆盖:
// ==UserScript== // ... 其他配置 ... // @run-at document-start // ==/UserScript==
内容的提问来源于stack exchange,提问作者패딩즈LYC
相关产品推荐
相关产品推荐

