Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...