frosty
frosty

Reputation: 2649

Can't use jQuery in tampermonkey

It keeps saying $ is not defined in tamper-monkey, even though I already @require the necessary link. What am I doing wrong?

// ==UserScript==
// @name         New Userscript
// @author       You
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
// @include https://www.google.com/
// ==/UserScript==

$(document).ready(function(){
  console.log('ready');
});

Upvotes: 1

Views: 5085

Answers (2)

Kxmode
Kxmode

Reputation: 270

You can use vanilla JS to load jQuery.

// Loads jQuery and triggers a callback function when jQuery has finished loading
function addJQuery(callback) {
    let script = document.createElement('script');
    script.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js');
    script.addEventListener('load', function() { callback(); }, false);
    document.body.appendChild(script);
}

// The main script
function main() {
     // put your tampermonkey code here
}

// Load jQuery and then execute the main function
addJQuery(main);

This loads on any site regardless of adblocker.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370729

Your adblocker appears to be blocking the https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js url. Either turn off the adblocker, or choose a different source for jQuery.

Once that's fixed, what you're seeing in the userscript interface is a linter warning, not a Javascript error. If you specify a page for the script to run on, the script will still run just fine. The warning is there to tell you that you haven't explicitly defined a $ variable yet; it doesn't know that what you've @required will define $.

To make the linter happy, tell it that $ is a global variable which is already defined:

...
// @include          https://example.com/
// ==/UserScript==

/* global $ */

$(document).ready(function(){
  console.log('ready');
});

Upvotes: 5

Related Questions