Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greasemonkey, overriding website functions

i've been reading a lot and have been trying to get this done for about 5 hours now... so here it is

I want to write a script that will override a function dummy() {$.ajax(...)}; on a website.

here is how i'm trying to do it

unsafeWindow.dummy = function(data){differantFunction(); $.ajax(...);};

function differantFunction(){
...
}

but the dummy function that would have been called up to do something on the original page... now just does nothing.

//update

I tried running that function i'm trying to override trough the adres bar to see what's wrong: (javascript:dummy("..");)

and I get an error telling me $ is undefined but I have jquery on the website and in the userscript... i'm so lost right now

like image 415
Mars Avatar asked Oct 31 '10 16:10

Mars


1 Answers

This happens because the script is running in GM scope.
If you don't use any GM function (like GM_setValue or GM_xmlhttpRequest), I recommend you to do the following:

var script = document.createElement('script'); 
script.type = "text/javascript"; 
script.innerHTML = (<><![CDATA[

// YOUR CODE GOES HERE

]]></>).toString();
document.getElementsByTagName('head')[0].appendChild(script);

Write the code as a normal script, not a GM script.
I mean, remove all unsafeWindow references and related stuff.
This will make the script to run in the correct scope.

BUT if you use GM functions, then you will need to add unsafeWindow before every variable in normal scope (like $) or do something like the following and pray to make it work:

$ = unsafeWindow.$;
//...

PS.: Multiline string with E4X is not supported anymore. Some other options are:
1) add your code into a function and then use Function.prototype.toString
2) create your code as a separate file and then add it as a resource
3) add a backslash at the end of each line

like image 107
w35l3y Avatar answered Oct 02 '22 03:10

w35l3y