【问题标题】:@require-ing jQuery overwrites the page's $ variable@require-ing jQuery 覆盖页面的 $ 变量
【发布时间】:2015-02-21 11:07:30
【问题描述】:

我是 @require-ing jQuery,我的 Greasemonkey 脚本在我的脚本文件中有这一行:

// @require https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js

而且效果很好;我可以使用$('#id') 访问 DOM。

但是,“真实”页面的$ 变量被修改(其中$ 是jQuery 1.2.xx): 我收到一个错误,$.include 未定义。

我以为 Greasemonkey 的沙盒模型可以防止目标页面的变量被覆盖?

如何确保包含的 javascript 库不会影响“真实”网站,而只会影响我的 Greasemonkey 脚本?

【问题讨论】:

    标签: jquery greasemonkey tampermonkey


    【解决方案1】:

    jQuery.noConflict();;它解释了很多。

    编辑:
    在搜索中找到"Greasemonkey 1.0 + jQuery: Broken, with Workaround"

    可能的解决方案:

     this.$ = this.jQuery = jQuery.noConflict(true);
    

    这样做,可能会隐式指定 $, jQuery 将在您的脚本的命名空间中可用。

    【讨论】:

    • 调用unsafeWindow.$.noConflict() 不会带回'旧' jQuery 版本,但在此调用之后$undefined。为什么首先被替换?
    • 因为你是通过unsafeWindow访问页面的js。我想你想在用户脚本上做$.noConflict();
    • 并非如此:页面的 js 引发了 $.include 未定义错误。
    • 我不相信noConflict() hack 在所有情况下都有效(但我现在不打算编写测试用例)。这是错误的方法,最稳健的解决方案是恢复沙箱。
    【解决方案2】:

    Greasemonkey 1.0, radically changed the way the sandbox works,破坏了数千个脚本。另请参阅jQuery in Greasemonkey 1.0 conflicts with websites using jQuery

    这是一个大问题,我希望你能和我一起在the principle bug report for this issue 上发表你的意见/经验。

    同时,将沙盒恢复到您的脚本,并解决 $ 冲突,方法是编辑您的 Metadata Block 以以下行结束

    // @grant       GM_addStyle
    // ==/UserScript==
    /*- The @grant directive is needed to work around a major design change introduced in GM 1.0,
        It restores the sandbox.
    */
    


    指定 @grant 值(none 除外)会重新激活沙箱。


    您也可以考虑切换到 Scriptish,它在过去提供了卓越的功能和性能,并且不会受到这种新沙盒行为的影响。

    【讨论】:

      猜你喜欢
      • 2015-03-12
      • 1970-01-01
      • 2015-04-23
      • 2014-07-23
      • 1970-01-01
      • 2011-09-21
      • 2022-06-16
      • 1970-01-01
      相关资源
      最近更新 更多