Tampermonkey jQuery require not working

て烟熏妆下的殇ゞ 提交于 2019-12-22 05:16:26

问题


I am trying to modify a piece of code I wrote for Grease Monkey to make it compatible with Tampermonkey. Tamper monkey keeps saying '$' is not defined despite my @require https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js. The require works on Greasemonkey.

The Tampermonkey instaled function(s) overview recognizes the JQuery require.

// ==UserScript==
// @name     Function
// @version  1
// @run-at   document-end
// @require  https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
// ==/UserScript==

var userIP;

$.ajax({
    url: "https://api.ipify.org/?format=json", // Getting user Ip Address
    async: false,
    dataType: 'json',
    success: function(data) {
        userIP = data.ip; // Saving user Ip Address
    }
});

回答1:


Since you say it is only in the editor this is probably Tampermonkey's syntax checking not loading required scripts, and using them as part of the code checking process. So it just sees that a variable has not been declared anywhere in the user script itself and shows the warning. The script should still work as expected.

If the messages annoy you, you can clear them by explicitly declaring the $ variable at the top of your script like so:

var $ = window.jQuery;//OR
var $ = window.$;



回答2:


Greasemonkey uses the CodeMirror text editor combined with the JSHINT linter.

In order for the JSHINT to recognize global variables declared outside of your code, you need to define them using an inline comment. For example, to tell JSHINT about jquery, use this:

/* globals $ */

See https://jshint.com/docs/#inline-configuration



来源:https://stackoverflow.com/questions/51090754/tampermonkey-jquery-require-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!