我是 javascript 和 chrome 扩展的新手(这是第一个应用程序)。 扩展获取打开页面 URL 的二维码。 对于 QRcode 生成,我使用这个库:https://github.com/jeromeetienne/jquery-qrcode 我在 SO 上阅读了一些 quides 和许多答案,但扩展不起作用。 所有*.js库都在根目录下,manifest.json
list .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"
}
}
弹出窗口
<!DOCTYPE html>
<html>
<head>
<title>basic example</title>
</head>
<body>
<script src="popup.js"></script>
</body>
</html>
弹出窗口
var pathname = window.location.pathname;
jQuery('#URLqrcodeCanvas').qrcode({
text : pathname
});
很可能我忘记了什么...
最佳答案
您的代码中几乎没有错误。让我们一步一步来
同时包含 jquery.qrcode.js 和 jquery.qrcode.min.js:在生产代码中,我们尝试使用缩小的 jquery,因为缩小的 js 文件的下载速度更快。
No element with selector used in popup.js :您正在尝试访问 popup.js 中的
URLqrcodeCanvas
,而弹出窗口中不存在此类元素。 HTML。也许你应该添加这个您没有在 popup.html 中包含 jquery 和 qrcode:您需要了解内容脚本、弹出脚本和后台脚本的上下文。读这个
SO Answer: Difference between popup script, background and content script
window.location.pathname 的错误使用:您可能想要访问当前事件选项卡的路径而不是弹出窗口。一旦您理解了弹出窗口和内容脚本之间的区别,那么您将很容易弄清楚这一点。读这个
感谢@Abraham 在此回答中添加第 3 点和第 4 点。希望对您有所帮助!!
关于javascript - 在内容脚本中定义但在弹出窗口中不可访问的脚本(Chrome 扩展),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22422932/