I have the following simple codes (partial):
manifest.json
"side_panel": {
"default_path": "sidepanel.html"
},
"action": {},
"permissions": ["sidePanel", "storage", "scripting", "tabCapture", "offscreen"]
background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
});
chrome.action.onClicked.addListener(async (tab) => {
// if you add the following code inside the onMessage.addListener
// you will get this error: "Unchecked runtime.lastError: The message port closed before a response was received"
// you should add the offscreen inside the onClicked event
const existingContexts = await chrome.runtime.getContexts({});
let recording = false;
console.log("[==] Context");
console.log(existingContexts);
console.log("[==] Context");
const offscreenDocument = existingContexts.find(
(c) => c.contextType === 'OFFSCREEN_DOCUMENT'
);
console.log("[==] Context offscreenDocument");
console.log(offscreenDocument);
console.log("[==] Context offscreenDocument");
// If an offscreen document is not already open, create one.
if (!offscreenDocument) {
console.log("[!!] Create offscreen document");
// Create an offscreen document.
await chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['USER_MEDIA'],
justification: 'Recording from chrome.tabCapture API'
});
}
});
offscreen.js
chrome.runtime.onMessage.addListener(async (message) => {
console.log("OFFSCREEN");
console.log(message);
console.log("OFFSCREEN");
});
sidepanel.js
document.getElementById('delete-button').addEventListener('click', function() {
console.log("Send Event Button Remove..");
chrome.runtime.sendMessage({action: 'RemoveTestButton'}, function(response) {
console.log(`message from background: ${JSON.stringify(response)}`);
});
});
The strange thing is that I can debug background.js and sidepanel.js but I cannot see any event on offscreen.js (which should be included by chrome.action.onClicked.addListener and the createDocument). In the chrome extension detail I can see background.js and sidepanel.html but not offscreen.html
I am a bit confused on to why this happens because as soon as I click the extension button the should include the offscreen.html file, but it's not.
Any idea what I am doing wrong?
Thanks
Setting the action click behavior to open a side panel (openPanelOnActionClick
) disables the chrome.action.onClicked event, so you should create the offscreen document in the side panel.
You may not need an offscreen document though: simply do everything in the side panel.