Chrome 中的 Tampermonkey - 如何在不影响网站的情况下使用 jquery

Tampermonkey in Chrome - How to use jquery without affecting the website at all

Google Chrome 中使用 Tampermonkey,我希望能够使用 jqueryset/get 值,但我需要确保没有任何东西是 changed/added到 dom.

简单来说,我希望 userscript 对受影响的网站绝对不可见

我添加的 jquery 是否对网站范围不可见?

另一个问题是,如果 jquery 已经存在怎么办?

我做的 @grants 对吗?

这是我的尝试

// ==UserScript==
// @name         test
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        *
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_setClipboard
// @grant unsafeWindow
// @grant window.close
// @grant window.focus
// ==/UserScript==

(function() {
    'use strict';

    //var $ = unsafeWindow.jQuery;
    var $ = window.jQuery;
    $(document).ready(Greasemonkey_main);

    function Greasemonkey_main ()
    {
    //$("#elem").val()    
    }


})();

如果您至少有一个 @grant 指令而不是 none,那将激活 Tampermonkey 的沙箱。此沙箱将导致 @required 个库将自己分配给 沙箱window,而不是 本机页面window,并在用户脚本代码中引用 window 变量将引用用户脚本的沙盒 window 而不是页面的原始 window.

如果您有 @grant none,这将表明 使用沙盒,并且 @requires 将导致属性被分配给原始 window(并且在用户脚本中引用 window 将引用原始的 window)。

由于您有一个启用沙箱的 @grant,并且您正在引用 window.jQuery,这将引用 jQuery 的沙箱版本,而无需对页面执行任何操作, 所以它应该按预期工作,不管 jQuery 是否已经在 native 页面上。 (因为你在沙盒中,所以不应该有任何冲突)