Reputation: 7696
I have a little Greasemonkey script that communicates with a servlet on (my) server. The servlet is sending back JavaScript code, which I eval() in the onload handler of the GM_xmlhttpRequest
.
So far, all is working fine. Now, I'd like to 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.
Upvotes: 1
Views: 993
Reputation: 1248
There is another solution. I have the similar problem, I don't want to put all my logic in user script, because if I change them, user need to update them by themselves. So what I want to do is separating the main logic from loading logic, the main logic will be loaded at beginning by the user script and eval them.
So I made a function "sendRequest", which is a wrapper of GM_xmlhttpRequest(), I need it anyway, because the method, server url and onError callback are always same for my application, so I just put them into my "sendRequest" function to make the xmlhttprequest simple.
In the main logic javascript code, which is loaded from server, there is no greasemonkey function call at all. If I want to for example communicate with server, I will call sendRequest instead. It works.
Upvotes: 0
Reputation: 18556
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.
Upvotes: 1
Reputation: 31928
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.
Upvotes: 1