kwah
kwah

Reputation: 1149

Parse Greasemonkey metadata and/or grab comments from within a function

function blah(_x)
{
  console.info(_x.toSource().match(/\/\/\s*@version\s+(.*)\s*\n/i)); 
}

function foobar()
{
  // ==UserScript==
  // @version    1.2.3.4
  // ==/UserScript==

  blah(arguments.callee);
}

foobar();

Is there any way to do this using JavaScript? I want to detect the version number / other attributes in a Greasemonkey script but as I understand it, .toSource() and .toString() strip out comments1.

I don't want to wrap the header block in <><![CDATA[ ]><> if I can avoid it, and I want to avoid having to duplicate the header block outside of the comments if possible.

Is this possible? Are there alternatives to toSource() / .toString() that would make this possible?

[1] - http://isc.sans.edu/diary.html?storyid=3231

Upvotes: 4

Views: 781

Answers (2)

Brock Adams
Brock Adams

Reputation: 93623

There is currently no really good way for a Greasemonkey script to know its own metadata (or comments either).   That is why every "autoupdate" script (like this one) requires you to set extra variables so that the script will know its current version.

As aularon said, the only way to get the comments from a JS function is to parse the source HTML of the <script> tag or of the file.

However, there is a trick that might work for you. You can read in your own GM script as a resource and then parse that source.

For example:

  1. Suppose your script was named MyTotallyKickassScript.user.js.

  2. Now add a resource directive to your script's metadata block like so:
    // @resource MeMyself MyTotallyKickassScript.user.js
    Notice that there is no path information to the file, GM will use a relative path to copy the resource, one time, when the script is first installed.

  3. Then you can access the script's code using GM_getResourceText(), like so:

    var ThisFileSource = GM_getResourceText ("MeMyself");  
    //Optional for Firebug users: console.log (ThisFileSource);
    
  4. You can parse ThisFileSource to get the comments you want.

  5. A script that parses Greasemonkey metadata from a source file is here. You should be able to adapt it with little effort.

Upvotes: 1

aularon
aularon

Reputation: 11110

Javascript engine will ignore comments, the only way to do that is to string process <script>'s innerHTML, or string process an AJAX request that fetches the .js file, if it was an external file.

Upvotes: 1

Related Questions