How to use jQuery in greasemonkey javascript scripts?

I saw a question here and a lot of blog posts about how to get jquery in greasemonkey, but I can't get anything to work.

Here is 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 hope to see a warning when I refresh the page, so I can start to program something. I have tried a bunch of other things, and so far nothing is working. The script is included in the little monkey menu ...

edit: now the script part looks like this:

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

he does not work. I know jQuery is good because I can run it from outside greasemonkey. If instead of jQuery function just say alert ('hello'); it works great; I get a warning when the page loads.

+4
source share
2 answers

Well, firstly, I would not embed jQuery in it. Just use the @require Greasemonkey directive (this should be in the script header).

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

In addition, you have jQuery assignment back. 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 .

+4
source

jQuery imported using @require seems to be located in an unsafe window of Windows.

0
source

Source: https://habr.com/ru/post/1300266/


All Articles