Chrome 扩展:从内容到后台脚本的消息传递
Chrome Extension: Message Passing from Content to Background Script
我已经搜索并尝试了 SO 对这个问题的不同可接受答案,但是 none 其中的答案适用于我的情况。我很确定我不明白什么。我在 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,在后台,侦听按钮发送的消息。
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 establish connection. Receiving end does not exist."
免责声明。如果我在 popup.js 上使用相同的按钮,它会下载图像。但我想将功能绑定到网站上注入的按钮上,而不是通过扩展面板。
目前您正在 page context which is both an unnecessary overcomplication and wrong as you inject the background script which already runs in the hidden separate background page of the extension that's not related to the web page. See how to open background.js devtools and console.
中注入代码
从 manifest.json 以及 jquery.js.
中删除 script_injection.js、injection_ui.js 和 web_accessible_resources
部分和不必要的权限
根据 documentation.
正确声明 onMessage 侦听器的参数
使用"persistent": false
,more info.
{
"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": ["content.js"],
"css": ["style.css"]
}],
"permissions": [
"storage",
"downloads"
],
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
让我们使用标准名称content.js,里面有标准的JS,没有jquery。如果你还想要jquery,那么在manifest.json中声明为"js": ["jquery.js", "content.js"]
content.js:
for (const thumb of document.querySelectorAll('.image-thumbnail')) {
thumb.appendChild(Object.assign(document.createElement('button'), {
className: 'DummyAddedButton',
textContent: 'Download',
}));
}
document.addEventListener('click', e => {
if (e.target.matches('.DummyAddedButton')) {
chrome.runtime.sendMessage(e.target.closest('.image-thumbnail').src);
}
});
background.js:
chrome.runtime.onMessage.addListener((message, sender, sendMessage) => {
chrome.downloads.download({url: message, filename: 'image.jpg'});
});
编辑 manifest.json 或内容脚本后,不要忘记在 chrome://extensions
页面和网页选项卡上重新加载扩展。
我已经搜索并尝试了 SO 对这个问题的不同可接受答案,但是 none 其中的答案适用于我的情况。我很确定我不明白什么。我在 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,在后台,侦听按钮发送的消息。
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 establish connection. Receiving end does not exist."
免责声明。如果我在 popup.js 上使用相同的按钮,它会下载图像。但我想将功能绑定到网站上注入的按钮上,而不是通过扩展面板。
目前您正在 page context which is both an unnecessary overcomplication and wrong as you inject the background script which already runs in the hidden separate background page of the extension that's not related to the web page. See how to open background.js devtools and console.
中注入代码从 manifest.json 以及 jquery.js.
中删除 script_injection.js、injection_ui.js 和web_accessible_resources
部分和不必要的权限
根据 documentation.
正确声明 onMessage 侦听器的参数使用"persistent": false
,more info.
{
"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": ["content.js"],
"css": ["style.css"]
}],
"permissions": [
"storage",
"downloads"
],
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
让我们使用标准名称content.js,里面有标准的JS,没有jquery。如果你还想要jquery,那么在manifest.json中声明为"js": ["jquery.js", "content.js"]
content.js:
for (const thumb of document.querySelectorAll('.image-thumbnail')) {
thumb.appendChild(Object.assign(document.createElement('button'), {
className: 'DummyAddedButton',
textContent: 'Download',
}));
}
document.addEventListener('click', e => {
if (e.target.matches('.DummyAddedButton')) {
chrome.runtime.sendMessage(e.target.closest('.image-thumbnail').src);
}
});
background.js:
chrome.runtime.onMessage.addListener((message, sender, sendMessage) => {
chrome.downloads.download({url: message, filename: 'image.jpg'});
});
编辑 manifest.json 或内容脚本后,不要忘记在 chrome://extensions
页面和网页选项卡上重新加载扩展。