[Greasemonkey] Variable Text Block

Edward Lee edilee at gmail.com
Fri Apr 15 17:29:06 EDT 2005

How are things being tossed around for the implementation of this
feature? I'm playing around with a hackish idea that puts data in
special tags that get parsed when loading the script.

One user script could look like this:

alert('>' + test + '<'); document.body.innerHTML = test2;
/*= test
lots of lines
yup yup
"quote me" 'too'
/*=test2 <input type="text" value="hello world!"/>=*/

It looks for a /*= followed by a variable name then optional newline
then data then another optional newline with =*/. The alert does have
">lots...!!<", so the extra newlines are trimmed, but only 1 gets
trimmed, so you could still have a newline at the end/beginning if you
wanted. Also, the page then gets replaced by the single input box with
hello world.

The changes to browser.xul is just in the injectScript function.

Basically, it's..

var extraVars = [];
for (var i = 0, matches =
    matches && i < matches.length; i++) {
  var varData = matches[i].match(/\/\*=\s*(\w+)\r?\n?([\s\S]+?)\r?\n?=\*\//);
  extraVars.push("var " + varData[1] + " = '" +
varData[2].replace(/\r/g, "\\r").replace(/\n/g,
"\\n").replace(/('|")/g, '\\$1') + "';\n");

runBrowserScript(doc, [ "(function(){",...     extraVars.join(''),
scriptContents,   ...].join("\n"));

The regular expressions could probably be cleaned up with the only
difference between the two is that one has the global modifier. The
variable name that gets matched could possibly be invalid, but that
could also happen elsewhere in the user script, so error checking
shouldn't be too big of an issue (but it does only allow
alphanumeric_). I suppose you can't have =*/ somewhere inside your
text block either.. Also, there are probably other things that need to
be escaped other than just \r \n ' ".

But doing all this does allow plain html with quotes and newlines and
all to be typed out at the end or anywhere in the user script to be
used in the user script. It just creates another variable in that
anonymous function scope, so it goes away at the end, but the script
can modify the contents if needed.


More information about the Greasemonkey mailing list