Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 702
Euphe Avatar asked Dec 28 '14 20:12

Euphe


People also ask

Where are Tampermonkey scripts stored?

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.


3 Answers

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();.

like image 104
Etheryte Avatar answered Sep 28 '22 11:09

Etheryte


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.

like image 31
Just a learner Avatar answered Sep 28 '22 11:09

Just a learner


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);
like image 32
Euphe Avatar answered Sep 28 '22 09:09

Euphe