【发布时间】:2021-03-31 09:48:29
【问题描述】:
我已经搜索并尝试了从 SO 到这个问题的不同可接受的答案,但它们都不适用于我的情况。我很确定我不明白一些事情。我在 24 小时前刚刚开始了这个 chrome 扩展之旅,所以我承认我有很多东西要学。
不过,我正在尝试为特定网站创建下载器。我有三个 javascript 文件:
- “script_injection.js”,添加在content_scripts.中,是一个纯javascript调用“injection_ui.js”据我了解,我不能直接在 content_scripts 上使用 chrome APIS,所以我创建了另一个 JS 文件并调用它。
- “injection_ui.js”,它是“web_accessible_resources”的一部分,将按钮添加到所有图像,并绑定了点击时消息传递的功能。李>
- background.js,在background中,监听按钮发送的消息。
manifest.json
{
"name": "Dummy Extension",
"version": "1.0",
"manifest_version": 2,
"description": "This is a dummy extension.",
"browser_action": {
"default_title": "Download Images from Anywhere",
"default_popup": "popup.html"
},
"content_scripts" : [
{
"matches": ["https://dummywebsite.com/*"],
"js": ["script_injection.js"],
"css": ["style.css"]
}
],
"permissions": [
"storage",
"downloads",
"activeTab",
"declarativeContent"
],
"web_accessible_resources": ["injection_ui.js"],
"background" : {
"scripts" : ["jquery.js", "background.js"],
"persistent" : true
}
}
script_injection.js
var s = document.createElement('script');
s.src = chrome.runtime.getURL('background.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
injection_ui.js
$(document).ready(function(){
$(".image-thumbnail").each(function(){
var src = $(this).attr("src");
$(this).append("<a class='DummyAddedButton' download='"+ src +"'>Download</button>");
});
$(".DummyAddedButton").off().on("click", function(){
var source = $(this).attr("src");
chrome.runtime.sendMessage("mlbcmjpahokfgkghabmfjgmnafffphpd", source, function(){
console.log("sending success: " + source);
});
});
});
background.js
chrome.runtime.onMessage.addListener(
function(message, callback) {
chrome.downloads.download({url:message, filename:"image.jpg"});
});
单击按钮时,它会根据 sendMessage 的指示在控制台日志上显示一条消息。但是,它也显示错误:“Unchecked runtime.lastError: Could not建立连接。接收端不存在。”
免责声明。如果我在 popup.js 上使用相同的按钮,它会下载图像。但我想将功能绑定在网站上注入的按钮上,而不是通过扩展面板。
【问题讨论】:
标签: google-chrome google-chrome-extension