views:

177

answers:

2

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.

+4  A: 

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.

John Feminella
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.
Mailslut
Working backwards from one of your scripts got me up and running. Used @require then wget jquery into the scripts directory.
tladuke
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.
Jayrox
A: 

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

visceroid