解析Greasemonkey元数据和/或从函数中获取注释 [英] Parse Greasemonkey metadata and/or grab comments from within a function

查看:89
本文介绍了解析Greasemonkey元数据和/或从函数中获取注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();

有没有办法使用JavaScript做到这一点?我想在Greasemonkey脚本中检测版本号/其他属性,但是据我了解,.toSource().toString()会删除注释 1 .

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.

如果可以避免的话,我不想将标题块包装在<><![CDATA[ ]><>中,并且如果可能的话,我想避免不得不在注释之外重复标题块.

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.

这可能吗? toSource()/.toString()是否有其他替代方法可以实现这一目标?

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

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

推荐答案

对于Greasemonkey脚本来说,目前尚没有真正好的方法来了解其自身的元数据(或注释).这就是为什么每个自动更新"脚本(像这样的 )都要求您设置额外变量的原因,该脚本将知道其当前版本.

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.

正如aularon所说,从JS函数中获取注释的唯一方法是解析<script>标签或文件的源HTML.

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.

但是,有一个窍门可能对您有用.您可以将自己的GM脚本作为资源读取,然后解析该源.

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.

例如:

  1. 假设您的脚本名为MyTotallyKickassScript.user.js.

现在将resource指令添加到脚本的元数据块,如下所示:
// @resource MeMyself MyTotallyKickassScript.user.js
请注意,该文件没有路径信息,一次安装 first 脚本时,GM将使用相对路径复制资源.

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.

然后,您可以使用 GM_getResourceText() 来访问脚本的代码,如下所示:

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);

  • 您可以解析ThisFileSource以获得所需的注释.

  • You can parse ThisFileSource to get the comments you want.

    用于解析源文件中Greasemonkey元数据的脚本在这里.您应该可以轻松调整它.

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

    这篇关于解析Greasemonkey元数据和/或从函数中获取注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆