繁体   English   中英

在内容脚本中使用JQuery

[英]Using JQuery in a content script

我试图在我的内容脚本中使用JQuery但是chrome控制台吐出这个“未捕获的ReferenceError:$未定义”。 我可以在我的后台脚本中成功使用JQuery,所以我不确定是什么意思。

这是清单文件:

{
    "name": "Something",
    "version": "1.0",
    "description": "SOmething",
    "background": {
        "scripts": ["background.js", "jquery.js"],
        "persistent": true
    },
    "browser_action": {
        "default_icon": "favicon.png",
        "default_popup": "popup.html"
    },
    "permissions": [
        "declarativeContent",
        "http://localhost/",
        "http://*/*",
        "https://localhost/",
        "https://*/*",
        "tabs"
    ],
    "icons": {
        "48": "icon-48p.png"
    },

    "content_scripts": [{
        "matches": [
            "http://*/*",
            "https://*/*"
        ],
        "js": ["content.js", "jquery.js"]
    }],
    "web_accessible_resources": ["button.PNG", "jquery.js"],
    "manifest_version": 2
}

这是内容脚本:

var btn = document.createElement("input");
btn.id = "btn";
btn.type = "image";
btn.setAttribute("src", chrome.extension.getURL("button.PNG"));
btn.onclick = function() {
    alert("Currently under development");
};
btn.className = "";


if (window.location.href.indexOf("mysite") > -1) {
    $('#pageContainer').append('<ol><li>CATS</li><ol>'); //Fails here

}


if (window.location.href.indexOf("myother") > -1) {
    document.getElementById("maindiv").appendChild(btn); //works
}

编辑:JQuery在项目中,它在background.js中工作。 问题是如何在我的内容脚本中使用它? 我在清单中指定了我希望jquery与content.js一起注入。

使jQuery成为content_scripts -> js数组中列出的第一个内容脚本。 喜欢:

"content_scripts": [{
    "matches": [
        "http://*/*",
        "https://*/*"
    ],
    "js": ["jquery.js", "content.js"]
}],

您的内容脚本在加载之前尝试访问jquery。 现在你的清单的设置方式,仍然应该加载jQuery。 要验证这一点,请在内容脚本页面的控制台中键入类似window.jQuery的内容,并确保已定义它。

正如berrberr指出的那样,你必须在content.js脚本之前加载jquery,如下所示

"js": ["jquery.js","content.js"]

或者你可以使用appendChild()在Pure JS中实现相同的功能。

另请注意:如果您正在操作DOM元素,请尝试在document_end处注入脚本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM