简体   繁体   English

“$”在 Chrome 扩展弹出窗口中未定义

[英]'$' is undefined in Chrome extension popup

I'm making my first Chrome extension, and ran into a problem using jQuery in a popup window.我正在制作我的第一个 Chrome 扩展程序,但在弹出窗口中使用 jQuery 时遇到了问题。 When I inspect the popup, I get an error the error: Uncaught ReferenceError: $ is not defined though I include my local copy of jQuery in manifest.json .当我检查弹出窗口时,我收到一个错误消息: Uncaught ReferenceError: $ is not defined尽管我在manifest.json包含了我的本地 jQuery 副本。 I am able to console.log within popup.js, but jQuery library apparently doesn't load.我可以在 popup.js 中使用 console.log,但 jQuery 库显然没有加载。 I searched related questions, but couldn't identify the problem - please advise我搜索了相关问题,但无法确定问题-请指教

manifest.json清单文件

{
    "manifest_version":2,
    "name":"extension",
    "version":"0.1",
    "content_scripts":[
        {
            "matches": [
                "<all_urls>"
            ],
            "js":["jquery-3.1.1.min.js","content.js","popup.js"]
        }],
    "browser_action":{
                "default_icon":"icon.png",
                "default_popup":"popup.html"
            }
        ,
    "background":{
        "scripts":["background.js"]
    }       

}

popup.html弹出窗口.html

<!DOCTYPE html>
<script src="popup.js"></script>
<div>
Search RT for Movie: <input type="text" value=""><input type="submit" id="bleh">
</div>

popup.js弹出窗口.js

$(document).ready(function(){
    function d(c){
        console.log(c)
    }
    d('hi')
    $('#bleh').click(function(){d('bi')})
})

Your content scripts are in a different context than your popup.您的内容脚本与弹出窗口处于不同的上下文中。 What you've loaded via your content_scripts entry in your manifest.json doesn't affect the context of your popup.您通过manifest.json中的content_scripts条目加载的内容不会影响弹出窗口的上下文。

You need to load jQuery into you popup.您需要将 jQuery 加载到弹出窗口中。 You can do so by adding a <script> tag for it:你可以通过为它添加一个<script>标签来实现:

popup.html : popup.html :

<!DOCTYPE html>
<script src="jquery-3.1.1.min.js"></script>
<script src="popup.js"></scrip>
<div>
    Search RT for Movie: <input type="text" value=""><input type="submit" id="bleh">
</div>

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

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