首页 > 解决方案 > Chrome 中的 Tampermonkey - 如何在不影响网站的情况下使用 jquery

问题描述

Tampermonkeyin 中Google Chrome,我希望能够使用jquerytoset/get值,但我需要确保没有任何内容被更改/添加到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()    
    }


})();

标签: javascriptjquerytampermonkeyuserscripts

解决方案


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

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

由于您有一个@grantwhich 正在启用沙箱,并且您正在引用window.jQuery,它将引用沙箱的 jQuery 版本,而不对页面做任何事情,所以它应该按需要工作,无论 jQuery 是否已经在本页面上或不是。(因为你在沙盒中,所以不应该有任何冲突)


推荐阅读