tags:

views:

442

answers:

2

Hi,

i have a little Greasemonkey script that communicates with a servlet on (my) server. The servlet is sending back javascript code, that i eval() in the onload handler of the GM_xmlhttpRequest.

So far, all is working fine. Now, for some reasons, i like use send another GM_xmlhttpRequest from within that eval()ed code. and here i'm stuck. i do not see any error, but all GM_* functions appear not to be working from within the eval(responsetext).

if i hard code the GM_xmlhttpRequest in the onload handler (no eval()), it is working fine.

i'm new to javascript and greasemonkey, so any help, links and so own would be greatly appreciated.

thanks in advance

A: 

Greasemonkey (GM) is hosting the user script, which means that it can add functions and objects to the user script, when you call eval() the script runs unhosted (the vanilla JavaScript is running it) and you don't get the GM API inside of it.

Shay Erlichmen
thanks for your reply. good to know that i do not need to wast more time looking for a bug in my code. not that i like the answer ;). but i understand that there are security reasons for this limitation.
bert
+1  A: 

It is possible to work around this problem, you can call GM_* functions with setTimeout set to 0 from eval'ed code. Try something like:

function myFunction() { GMXmlHttpRequest(...) }

eval('setTimeout(myFunction, 0)');

A better solution is to extend Function.prototype with a function called safeCall that does this for you. Whenever you have any eval'ed code that will call into GM_* functions you'll need to have safeCall somewhere in that call chain.

dnolen
thanks. what i was trying to archive was a some additional check to prevent people tampering with the data being send to my servlet. for this, i wanted an additional round trip sending an security token, but with out a trace for this in the gm script. as this is not working, i guess it is better to play open (having traces (in you myFunction() suggestion could make users nervous) and just have the GMXmlHttpRequest() plain in the script and just receive/send a security token.thanks again for your answer
bert
Why does `eval('setTimeout(myFunction, 0)');` work but `eval('setTimeout(function(){myFunction()}, 0)');` doesn't? I need to call `myFunction` with some params, how should I do that?
Paul Tarjan