164

I am writing a script which logs into my college network when the login page is loaded.

The code looks as follows

// ==UserScript==
// @name       My Fancy New Userscript
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description  enter something useful
// @match      <College login page>
// @copyright  2012+, You
// ==/UserScript==    
$(document).ready(function() {

    var usr=document.getElementsByName("username");

    var pass = document.getElementByName("password");

    usr.value="usrname";    
    pass.value="password";    

    var submitButton = document.querySelector ('input[type="submit"][value="Login"]');

    var clickEvent  = document.createEvent ('MouseEvents');

    clickEvent.initEvent ('click', true, true);

    submitButton.dispatchEvent (clickEvent);

    });

The console shows a error saying

$ is not defined

Can someone tell me what is going on here?

Jonah
  • 2,097
  • 4
  • 20
  • 22

2 Answers2

361

You need to have a @require in the user script header to load jQuery. Something like:

// @require https://code.jquery.com/jquery-3.6.0.min.js

(Selecting your desired version from the of list of available versions of jQuery)

Métoule
  • 13,062
  • 2
  • 56
  • 84
Aardvark99
  • 3,626
  • 1
  • 12
  • 2
14

For future googlers,

If you have used the above method and still jQuery doesn't seem to be loaded by your script try looking at the spaces, And try to match the indentation with the rest of the header. Apparently the indentation is important.

Faulty:

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://stackoverflow.com/*
// @require http://code.jquery.com/jquery-3.4.1.min.js 
// @grant        none
// ==/UserScript==

Correct:

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://stackoverflow.com/*
// @require      http://code.jquery.com/jquery-3.4.1.min.js 
// @grant        none
// ==/UserScript==
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • Thanks for this! Just a thought: can't the accepted answer be edited instead of an extra post ? – deryb Apr 01 '22 at 11:34
  • 1
    By that logic, every answer would end up with just one very long answer edited over time. Don't you think? – Mohd Abdul Mujib Apr 01 '22 at 12:33
  • to be honest, a comment like "take care of indent when inserting @require" would also be enough and could easily be edited. and i agree a bit with your statement in the comment above, but on the other hand, if every question had several answeres, than the answere isnt good enough. even one LONG answere is may just bad explained ^^ – Dwza Jul 19 '22 at 09:39