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 were stored in a special SQLite database and were/are not directly editable in file form. Update: As of version 3.5. 3630, Tampermonkey scripts are now stored using Chrome's extension storage.
Tampermonkey scripts are run in a separate scope. 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();
.
A better way do to that is to grant unsafeWindow
.
// @grant unsafeWindow
Then create your function like this:
function test()
{
console.log("test");
}
But also make it available in console through unsafeWindow
:
if(!unsafeWindow.test)
{
unsafeWindow.test = test;
}
Then you can access test
in the console.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With