7

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

Mars
  • 4,197
  • 11
  • 39
  • 63

1 Answers1

12

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

Community
  • 1
  • 1
w35l3y
  • 8,613
  • 3
  • 39
  • 51
  • I found a bug in Firebug console, you can't set a breakpoint in a method overridden with Greasemonkey :/ – baptx Jun 22 '12 at 10:58
  • I can't seem to get this to work at all - could it be because I'm trying to override an event handler? – Jack M Jun 18 '13 at 14:20
  • You may try to remove the current event handler and add a new one. Ask your own question with some example. – w35l3y Jun 20 '13 at 11:54
  • To get very easy multiline support, just use the new "template literals". `script.innerHTML = \` multiple lines \` `. Please note the "backticks" >> \` <<. – user136036 Feb 23 '18 at 01:55