当我正在处理我的铬扩展时,我得到了一个错误"$是未定义的“。
这是我的清单文件:
{
"name": "X",
"description": "Snip this page",
"version": "2.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts":[{
"matches" : ["<all_urls>"],
"js": ["jquery-2.0.2.js","jquery.Jcrop.js"],
"css": ["jquery.Jcrop.min.css"]
}],
"browser_action": {
"default_title": "Snip this page"
},
"manifest_version": 2
}这是我的background.js文件:
chrome.browserAction.onClicked.addListener(function(tab){
// No tabs or host permissions needed!
chrome.tabs.executeScript({
file: 'content.js'
});
});最后,触发错误的文件: content.js
console.log('1');
var jcropapi, boundx, boundy;
$('body').attr('id', 'target');
$(document).ready(function(){
$('target').Jcrop();
console.log('4');
document.onkeydown = function(){
if(window.event.keyCode==13){
console.log('enter');
}
};
});据我理解,之所以会出现这种情况,是因为JQuery没有加载。但是,我正在清单中正确地加载它,jquery.js也是清单内容脚本中调用的第一个文件。请帮助我调试。谢谢!
发布于 2013-10-05 17:42:42
我不知道它是如何工作的,但不知怎么的,当我将JQuery更改为它的最小化版本时,它现在开始工作了。
发布于 2014-10-30 08:08:02
当调用jQuery的脚本在加载jQuery.js之前加载时,就会发生这种情况。在问题提交者给出的示例中,背景加载在内容脚本之前,内容脚本在后台脚本调用jQuery之后加载jQuery本身。可以通过让后台脚本加载jQuery本身来修复此示例,如下所示:
"background": {
"scripts": ["jquery-2.0.2.js", "jquery.Jcrop.js", "background.js"],
"persistent": false
}, 还请记住,清单中列出的js文件是按照它们显示的顺序加载的。例如,假设您有一个文件"script.js",它包含:
console.log($('#elementID'));如果您像这样编写清单(错误),您将得到错误"$不是定义的“:
"content_scripts": [
{
"js": [
"script.js",
"jquery.js" ]
}
]将清单更改为此(右)将修复错误:
"content_scripts": [
{
"js": [
"jquery.js",
"script.js" ]
}
]请注意,"jquery.js“现在位于"script.js”之前,因此首先加载。
这个问题似乎是断断续续的,因为两个脚本几乎同时加载。如果您更改了脚本,使对jQuery的调用低于其他一些javascript命令,那么执行这些其他命令所需的时间可能就足以使jQuery.js完成加载。因此,例如,如果您以错误的方式编写清单,您还可以通过如下方式更改script.js文件,从而在技术上修复错误:
var t = setTimeout(function(){
console.log($('#elementID'));
}, 1000);1秒的延迟给jQuery.js足够的时间加载,然而,这显然不是理想的解决方案!
发布于 2020-09-03 07:07:30
之所以发生这种情况,是因为在jQuery文件之前调用脚本。
正确的办法是:
{
"name": "X",
"description": "Snip this page",
"version": "2.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts":[{
"matches" : ["<all_urls>"],
"js": ["jquery-2.0.2.js","yourscript.js"],
"css": ["jquery.Jcrop.min.css"]
}],
"browser_action": {
"default_title": "Snip this page"
},
"manifest_version": 2
}https://stackoverflow.com/questions/19199956
复制相似问题