我正在处理Chrome扩展程序,并且在注入的内容脚本和后台页面之间的通信方面遇到了问题。我可以将所选元素传递给内容脚本,但是我没有收到尝试发送回扩展的测试响应。我确定我错过了一些非常明显的东西,但我找不到它。
devtools.js
var panels = chrome.devtools.panels;
var panel = panels.elements.createSidebarPane("Field Info",
function(sidebar) {
// sidebar initialization code here
sidebar.setPage("fields.html")
});
panels.elements.onSelectionChanged.addListener(function(){
chrome.devtools.inspectedWindow.eval("setSelectedElement($0)",
{ useContentScriptContext: true });
});
contentscript.js
function setSelectedElement(el) {
console.log(el); //Shows up
window.postMessage({
name: "abcde"
});
}
background.js
chrome.runtime.onConnect.addListener(function(devToolsConnection) {
// assign the listener function to a variable so we can remove it later
var devToolsListener = function(message, sender, sendResponse) {
// Inject a content script into the identified tab
log(message);
chrome.tabs.executeScript(message.tabId,
{ file: message.scriptToInject });
}
// add the listener
devToolsConnection.onMessage.addListener(devToolsListener);
devToolsConnection.onDisconnect.addListener(function() {
devToolsConnection.onMessage.removeListener(devToolsListener);
});
});
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
log(message);
});
function log(message){
console.log(message);
}
知道我可能缺少什么吗?