在用于firefox的网络扩展中,我尝试使用以下代码将消息从后台脚本发送到侧边栏panel.js:
let url = browser.runtime.getURL("/sidebar/panel.html");
if (logToConsole) console.log(`Panel url for EXIF tags is ${url}`);
browser.sidebarAction.setPanel({panel: url});
browser.sidebarAction.setTitle({title: "EXIF tags"});
browser.sidebarAction.open()
.then(()=>{
browser.tabs.query({currentWindow: true})
.then((tabs)=>{
sendMessageToTabs(tabs, {"action": "displayExifTagsInSidebar", "data": {"imageUrl": imageUrl, "imageTags": imageTags}});
})
.catch((err)=>{
if (logToConsole) console.error(err);
});
})
.catch((err)=>{
if (logToConsole) console.error(err);
});
它导致以下错误: “ 错误:”无法建立连接。接收端不存在。” sendMessageToTab moz-extension://c74377ac-91c8-c043-87f9-5021b480dcec/scripts/background.js:1084:13“
在尝试使用browser.runtime.sendMessage(message)而不是browser.tabs.sendMessage(tabId,message)时,我遇到了同样的问题。
应在侧栏中加载的panel.html文件如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../styles/panel.css"/>
</head>
<body>
<div id = "content"></div>
<script src="../scripts/panel.js"></script>
</body>
</html>
并且panel.js包含如下消息处理程序:
/// Message handlers
browser.runtime.onMessage.addListener(handleMessage);
function handleMessage(message) {
let action = message.action;
let imageUrl = message.data.imageUrl;
let imageTags = message.data.imageTags;
switch (action) {
case "displayExifTagsInSidebar":
createExifTagsPage(imageUrl, imageTags);
break;
default:
break;
}
}
function createExifTagsPage(imageUrl, imageTags){
// more code here... not relevant!
}