As some of you may know, Google Chrome has put some severe limitation on Greasemonkey scripts.
Chromium does not support
@require
,
I have written a few functions based on the Erik Vold's script to help run me run functions, code and other scripts in a document. You can use them to load jQuery into the page and then run code under the global window
scope.
// ==UserScript==
// @name Example from http://stackoverflow.com/q/6834930
// @version 1.3
// @namespace http://stackoverflow.com/q/6834930
// @description An example, adding a border to a post on Stack Overflow.
// @include http://stackoverflow.com/questions/2246901/*
// ==/UserScript==
var load,execute,loadAndExecute;load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},loadAndExecute=function(a,b){return load(a,function(){return execute(b)})};
loadAndExecute("//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
$("#answer-6834930").css("border", ".5em solid black");
});
You can click here to install it, if you trust that I'm not trying to trick you into installing something malicious and that nobody has edited my post to point to something else. Reload the page and you should see a border around my post.
load(url, onLoad, onError)
Loads the script at url
into the document. Optionally, callbacks may be provided for onLoad
and onError
.
execute(functionOrCode)
Inserts a function or string of code into the document and executes it. The functions are converted to source code before being inserted, so they lose their current scope/closures and are run underneath the global window
scope.
loadAndExecute(url, functionOrCode)
A shortcut; this loads a script from url
, then inserts and executes functionOrCode
if successful.
function load(url, onLoad, onError) {
e = document.createElement("script");
e.setAttribute("src", url);
if (onLoad != null) { e.addEventListener("load", onLoad); }
if (onError != null) { e.addEventListener("error", onError); }
document.body.appendChild(e);
return e;
}
function execute(functionOrCode) {
if (typeof functionOrCode === "function") {
code = "(" + functionOrCode + ")();";
} else {
code = functionOrCode;
}
e = document.createElement("script");
e.textContent = code;
document.body.appendChild(e);
return e;
}
function loadAndExecute(url, functionOrCode) {
load(url, function() { execute(functionOrCode); });
}