简体   繁体   中英

'$' is undefined in Chrome extension popup

I'm making my first Chrome extension, and ran into a problem using jQuery in a popup window. 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 . I am able to console.log within popup.js, but jQuery library apparently doesn't load. 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

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

popup.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.

You need to load jQuery into you popup. You can do so by adding a <script> tag for it:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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