简体   繁体   中英

Scripts defined in content scripts but not accessible in popup (Chrome extension)

I'm new in javascript and chrome extensions (this is first application). Extension get a QRcode of the open page's URL. For QRcode generation I use this lib: https://github.com/jeromeetienne/jquery-qrcode I read some quides and many answers on SO, but extension doesn't work. All *.js libraries are in the root catalog with manifest.json

manifest.json

{
"manifest_version": 2,

"name": "QRify",
"description": "This extension shows a QR code of the open page",
"version": "1.0",

"content_scripts": [
    {
        "matches": ["http://www.google.com/*"],
        "js": [
            "jquery.min.js",
            "jquery.qrcode.js",
            "jquery.qrcode.min.js",
            "qrcode.js"
            ]
    }
],  
"browser_action":{
    "default_icon": "icon.png",
    "default_popup": "popup.html"
}
}

popup.html

<!DOCTYPE html>
<html>
<head>
<title>basic example</title>
</head>
<body>

<script src="popup.js"></script>

</body>
</html>

popup.js

var pathname = window.location.pathname;
    jQuery('#URLqrcodeCanvas').qrcode({
    text    : pathname
}); 

Most likely I forgot something...

There are few things which are wrong in your code. Let's take them step by step

  1. Inclusion of both jquery.qrcode.js and jquery.qrcode.min.js : In production code, we try to use minified jquery because downloading of minified js files is faster.

  2. No element with selector used in popup.js : You are trying to access URLqrcodeCanvas in your popup.js while no such element is present in popup.html. May be you should add this

  3. You have not included jquery and qrcode in your popup.html : You need to understand the context of content script, popup scripts and background scripts. Read this

    SO Answer: Difference between popup script, background and content script

  4. Wrong use of window.location.pathname : May be you wanted to access the path of current active tab instead of popup. Once you understand the difference between popup and content script then you will be easily figure out this point. Read this

    SO Answer: How to get url of active tab ?

Thanks to @Abraham for adding points 3 and 4 in this answer. Hope it helps!!

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