我有一个 chrome 扩展程序,想要使用最近添加的 chrome.sidePanel API 打开侧面板,并在用户单击扩展程序弹出窗口内的按钮时在其中显示我的 chrome 扩展程序。
我尝试过以下代码:
应用程序.tsx
const handleOpenSidePanel = async () => {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
const currentTabId = tabs[0].id;
chrome.runtime.sendMessage({ type: 'openSidePanel', tabId: currentTabId });
});
}
背景.js
chrome.runtime.onMessage.addListener((message, tab) => {
if (message.type === "openSidePanel") {
chrome.sidePanel.open({ windowId: tab.windowId});
}
});
manifest.json
"permissions": [
"sidePanel",
"tabs"
],
"side_panel": {
"default_path": "index.html"
}
...
当我单击按钮时,出现以下错误并且侧面板未打开:
Uncaught (in promise) Error: At least one of "tabId" and "windowId" must be provided
你有两个选择,
添加到service-worker.js:
chrome.sidePanel
.setPanelBehavior({ openPanelOnActionClick: true })
.catch((error) => console.error(error));
在这种情况下,您的清单版本 3 具有以下属性:
添加到manifest.json:
"background": {
"service_worker": "service-worker.js"
},
"side_panel": {
"default_path": "sidepanel-global.html"
},
"action": {
"default_popup": "popup.html"
},
"permissions": ["sidePanel"],
然后弹出窗口上有一个按钮(id =“openSidePanel”),单击该按钮时会向服务工作线程发送一条消息。
添加到popup.js:
document.getElementById('openSidePanel').addEventListener('click', function() {
chrome.runtime.sendMessage({action: 'open_side_panel'});
});
Service Worker 会收到消息,但在此之前,您需要确保将 Windows 选项卡信息传递给 Service Worker:
添加到service-worker.js:
// to find the windowId of the active tab
let windowId;
chrome.tabs.onActivated.addListener(function (activeInfo) {
windowId = activeInfo.windowId;
});
// to receive messages from popup script
chrome.runtime.onMessage.addListener((message, sender) => {
(async () => {
if (message.action === 'open_side_panel') {
chrome.sidePanel.open({ windowId: windowId });
}
})();
});
在这里您可以找到更多选项:Chrome 侧面板、为什么 sendMessage 不传递 tabId