Javascript 如何将消息从popup.html发送到内容脚本?
我正在进行扩展,希望将消息从popup.html传递到content.js,但是下面的代码警报未定义。请给我一个简单的脚本,将消息从popup.html发送到content.js,反之亦然,我将进一步处理它。我想通过这个扩展访问DOM,以修改和设计网站布局 清单Javascript 如何将消息从popup.html发送到内容脚本?,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我正在进行扩展,希望将消息从popup.html传递到content.js,但是下面的代码警报未定义。请给我一个简单的脚本,将消息从popup.html发送到content.js,反之亦然,我将进一步处理它。我想通过这个扩展访问DOM,以修改和设计网站布局 清单 { "manifest_version": 2, "name": "Extension", "description": "Description", "version": "1.0", "background":
{
"manifest_version": 2,
"name": "Extension",
"description": "Description",
"version": "1.0",
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [{
"matches": ["*"],
"js": ["content.js"]
}],
"browser_action": {
"default_icon": "icons/icon.png",
"default_popup": "popup.html"
},
"permissions":["tabs"]
}
popup.js
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('button').onclick=function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
alert(response);
});
});
}
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
Content.js
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('button').onclick=function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
alert(response);
});
});
}
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
试试这个简单的代码
manifest.json
popup.html
content.js
警觉的
您的代码对我有效。您是否在此处重新加载了扩展名
chrome://extensions/
?它在警报中返回什么?它警报对象和警报(response.fore)代码>提醒再见。相信我,此处不起作用。请在回答中跳过相同的代码。这会导致错误“接收端不存在”。也许您没有重新加载页面。看到这个帖子了吗
document.getElementById("set").onclick = function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
alert(response.farewell);
});
});
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});