Milos
Milos

Reputation: 2946

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

With Tampermonkey in Google Chrome, I want to be able to use jquery to set/get values but I need to make sure nothing is changed/added to the dom.

In simple words, I want userscript to be absolutely invisible to the affecting website.

Is the jquery that I added invisible to the website scope?

Another concern is, what if jquery is already present?

Did I do the @grants right?

Here is my try

// ==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()    
    }


})();

Upvotes: 1

Views: 519

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

If you have at least one @grant directive other than none, that will activate Tampermonkey's sandbox. This sandbox will result in @required libraries assigning themselves to the sandbox's window, rather than on the native page's window, and referencing the window variable inside the userscript code will refer to the userscript's sandboxed window rather than the page's original window.

If you have @grant none, this will indicate not to use the sandbox, and @requires will result in properties being assigned to the original window (and referencing window inside the userscript will be referring to the original window).

Since you have a @grant which is enabling the sandbox, and you're referencing window.jQuery, that will reference the sandbox's version of jQuery, without doing anything to the page, so it should work as desired, regardless of whether jQuery is already on the native page or not. (Because you're in the sandbox, there shouldn't be any conflicts)

Upvotes: 4

Related Questions