So I'm going to publish my Tampermonkey userscript (It's a button to get you to a random link in the list) to the Chrome Web Store, I have been testing it today and I got an error:
Uncaught TypeError: $ is not a function
at Chain Finder.user.js:258
at Chain Finder.user.js:261
If you want to take a look at my script:
(function() {
const $ = window.$;
var randomLink = function () {
// Beggining of target list
var links = [
"torn.com/profiles.php?XID=2410074",
"torn.com/profiles.php?XID=2393322",
"torn.com/profiles.php?XID=2049797",
"torn.com/profiles.php?XID=2268673",
"torn.com/profiles.php?XID=2059647"
// More links.... but I cut them so it's easier to understand.
];
// End of target list
// by counting the number of links in the array
var max = (links.length)
// now generate a random number
var randomNumber = Math.floor(Math.random()*max);
// use that random number to retrieve a link from the array
var link = links[randomNumber];
// change the location of the window object
return "https://" + link;
}
// Opens a new tab.
function openInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();
}
function main() {
$('.buttons-list').append(`<a id="mc-btn" href="#" class="profile-button" style="width:99px;text-align:center">
<img src='https://i.imgur.com/TQdk3Pp.png'>
</a>`);
$('#mc-btn').on('click', () => openInNewTab(randomLink()));
}
//Here's the error:
$(document).ready(() => {
main();
});
})();
If you could tell me what's wrong in there, I will be very grateful.
Edit: I've learned JavaScript. It all seems so easy now! Thank you for the help either way.
Make sure that somewhere in your script that you include these two lines of code, put var $ = window.jQuery; above where you code starts, and put // @require http://code.jquery.com/jquery-3.4.1.min.js somewhere up top with the rest of the // lines.
Example:
// ==UserScript==
// @name Example
// @namespace http://tampermonkey.net/
// @version 0.1
// @description
// @author Username
// @require http://code.jquery.com/jquery-3.4.1.min.js
// @grant GM_addStyle
// @grant GM.listValues
// @grant GM_setValue
// @grant GM_getValue
// @match *
// @match https://*/*
// @match http://*/*
// @match *://*/*
// ==/UserScript==
(function() {
'use strict';
// Your code here...
})();
var $ = window.jQuery;