views:

68

answers:

2
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

+1  A: 

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.

aularon
This is for within a Greasemonkey script which makes it not possible (to my knowledge) to do this as you suggest
kwah
+1  A: 

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.

Brock Adams
That is actually a pretty damn awesome trick - one of those "why didn't I think of that" kind of things =]
kwah
Just a quick note for anybody else reading, scripts uploaded to userscripts.org get renamed to their {scriptID}.user.js resulting in an error on install if you don't predict the filename correctly ;)
kwah