4

I saw a question here and many blog posts about getting jquery into greasemonkey, but I can't get anything to work.

Here's my script:

// ==UserScript==
// @name          Hello jQuery
// @namespace     http://foo.bar
// @description   jQuery test script
// @include       *
// ==/UserScript==

#{contents of jquery.latest.js pasted in}

unsafeWindow.jQuery = jQuery;

$(document).ready(function() {
    alert('Hello world!');
});

I'm hoping to see an alert when I refresh a page, so I can start actually programming something. I've tried a bunch of other things and so far nothing works. The script is enabled in the little monkey menu...

edit: the script part now looks like this:

foo();

function foo() {
    $ = unsafeWindow.jQuery;
    $('tr td.row2:nth-child(4)').css("background-color", "#999");
}

it doesn't work. I know the jQuery is good because I can run it from outside of greasemonkey. If instead of a jQuery function is just say alert('hello'); that works fine; I get the alert on page-load.

2 Answers 2

4

Well, first off, I wouldn't paste jQuery into it. Just use the @require Greasemonkey directive (this must be in your script header).

// @require        http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js  

Also, you have the jQuery assignment backwards. It should be more like:

function foo() {
  $ = unsafeWindow.jQuery;
  // or jq = unsafeWindow.jQuery, or whatever you'd like to call it

  ...
}

This is what I usually do in my scripts.

Sign up to request clarification or add additional context in comments.

3 Comments

Using @require is the correct way to do it (make sure you have a relatively up to date version of greasemonkey as this featured hasn't always been around). Also worth noting, is that the @require string must be present when you INSTALLED the greasemonkey script, editing the greasemonkey script once installed to add the @require wont work. So if your script is already installed, uninstall it and add the @require part before reinstalling. You can edit the rest of the script as normal without reinstalling.
Working backwards from one of your scripts got me up and running. Used @require then wget jquery into the scripts directory.
you could put the greasemonkey loading code into a html file and save it to your desktop or a webserver and install it from there.
0

jQuery imported using @require seems to reside in window not unsafeWindow.

1 Comment

I'm using jquery 1.8.1 and tampermonkey (chrome) and I need to use unsafeWindow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.