I am writing a userscript that is injected into a webpage. The script reads some data from a web-server and I want to send messages to a listening application to react to the data.
For now, all I'm doing is trying to send a string command to my listening application and see if I can read it. My code worked before it was injected, but afterwards I get an "undefined reference error".
I suspect that this has something to do with this "Greasemonkey access violation". However, I have been unable to find a solution that works. I'm developing in Chrome.
Here is the section of code I can't get to work.
GM_xmlhttpRequest({
method: "POST",
url: "http://localhost:7777",
data: "testing123",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function(response)
{
if (response.responseText.indexOf("TEST") > -1)
{
console.log("Response confirmed...");
}
}
});
I'm pretty new to scripting so maybe I'm missing something obvious. How do I get this to work in injected code?
GM_
functions will not work in injected code because injected code runs in the target page's scope. If they did work there, then unscrupulous web-sites could also use the GM_
functions -- to do unspeakable evil.
The solutions, most preferable first:
Don't inject code. Much of the time, it really isn't necessary, and it always complicates things. Only inject code if you absolutely, positively need to use some of the javascript loaded by the target page.
For libraries like jQuery, you will get better performance using the @require
directive (Firefox), or pasting-in the library code or using a custom manifest.json file to include it (Chrome).
By not injecting code, you:
GM_
functionsGM_
functions.
Use the Tampermonkey extension (Chrome). This allows you to avoid script injection by providing better Greasemonkey emulation. You can use the @require
directive and a more powerful/risky version of unsafeWindow
than Chrome natively provides.
Split your userscript code into injected parts -- which cannot use GM_
functions -- and non-injected parts. Use messaging, polling, and/or a specific DOM node to communicate between the scopes.
If you really must use injected code, here's a sample script that shows how to do it:
// ==UserScript==
// @name _Fire GM_ function from injected code
// @include https://stackoverflow.com/*
// @grant GM_xmlhttpRequest
// ==/UserScript==
/* Warning: Using @match versus @include can kill the Cross-domain ability of
GM_xmlhttpRequest! Bug?
*/
function InjectDemoCode ($) {
$("body").prepend ('<button id="gmCommDemo">Open the console and then click me.</button>');
$("#gmCommDemo").click ( function () {
//--- This next value could be from the page's or the injected-code's JS.
var fetchURL = "http://www.google.com/";
//--- Tag the message, in case there's more than one type flying about...
var messageTxt = JSON.stringify (["fetchURL", fetchURL])
window.postMessage (messageTxt, "*");
console.log ("Posting message");
} );
}
withPages_jQuery (InjectDemoCode);
//--- This code listens for the right kind of message and calls GM_xmlhttpRequest.
window.addEventListener ("message", receiveMessage, false);
function receiveMessage (event) {
var messageJSON;
try {
messageJSON = JSON.parse (event.data);
}
catch (zError) {
// Do nothing
}
console.log ("messageJSON:", messageJSON);
if ( ! messageJSON) return; //-- Message is not for us.
if (messageJSON[0] == "fetchURL") {
var fetchURL = messageJSON[1];
GM_xmlhttpRequest ( {
method: 'GET',
url: fetchURL,
onload: function (responseDetails) {
// DO ALL RESPONSE PROCESSING HERE...
console.log (
"GM_xmlhttpRequest() response is:\n",
responseDetails.responseText.substring (0, 80) + '...'
);
}
} );
}
}
function withPages_jQuery (NAMED_FunctionToRun) {
//--- Use named functions for clarity and debugging...
var funcText = NAMED_FunctionToRun.toString ();
var funcName = funcText.replace (/^function\s+(\w+)\s*\((.|\n|\r)+$/, "$1");
var script = document.createElement ("script");
script.textContent = funcText + "\n\n";
script.textContent += 'jQuery(document).ready( function () {' + funcName + '(jQuery);} );';
document.body.appendChild (script);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With