[英]How do I make functions added by Tampermonkey be available in console after the script has been ran?
I made a script that among other things has a function in it: 我创建了一个脚本,其中包含一个函数:
function updateGUI(){
document.getElementById("cursoft").value = getSoftware();
document.getElementById("curver").value = getCurrentVersion();
document.getElementById("rcycles").value = getResearchCycles();
document.getElementById("rcycle").value = getCurrentCycle();
document.getElementById("curproc").value = getCurrentProcess();
document.getElementById("curact").value = getCurrentAction();
}
The script runs on page load just fine, but when I try to run this function after the script finishes execution it's "undefined". 该脚本在页面加载时运行很好,但是当我尝试在脚本完成执行后运行此函数时,它是“未定义”。
How can I make it "stay" in the current scope? 如何让它“保持”在当前范围内?
Tampermonkey scripts are run in a separate scope. Tampermonkey脚本在单独的范围内运行。 This means that to make a function available globally you'll want to do something along the following:
这意味着要使全局可用的功能,您需要执行以下操作:
window.updateGUI = function () {...}
If you want to add a number of functions to the global scope, it's better to store them under a single object and address your functions through there. 如果要向全局范围添加许多函数,最好将它们存储在单个对象下并通过那里解决您的函数。 That helps avoid any possible collisions you might otherwise have.
这有助于避免您可能遇到的任何可能的冲突。
var myFunctions = window.myFunctions = {};
myFunctions.updateGUI = function () {...};
After that you can simply call myFunctions.updateGUI();
之后你可以简单地调用
myFunctions.updateGUI();
. 。
A better way do to that is to grant unsafeWindow
. 更好的方法是授予
unsafeWindow
。
// @grant unsafeWindow
Then create your function like this: 然后像这样创建你的函数:
function test()
{
console.log("test");
}
But also make it available in console through unsafeWindow
: 但也可以通过
unsafeWindow
在控制台中使用它:
if(!unsafeWindow.test)
{
unsafeWindow.test = test;
}
Then you can access test
in the console. 然后,您可以在控制台中访问
test
。
I found an answer to my question, but Nit's answer is superior. 我找到了我的问题的答案,但尼特的答案更胜一筹。 I will still post mine in case someone needs it.
如果有人需要,我仍然会发布我的。
You can add functions to global scope by adding them to a script element and appending it to body 您可以通过将函数添加到脚本元素并将其附加到正文来向全局范围添加函数
var scriptElem = document.createElement('script');
scriptElem.innerHTML = 'function updateGui() { /* stuff */ }';
document.body.appendChild(scriptElem);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.