Reputation: 6324
I have an App page (extension_id://app.html) I want to create a new tab:
let tab = await chrome.tabs.create({ url: candidate_url });
chrome.tabs.sendMessage(tab['id'], {"message": "sendMessage", "data": {}, "tabID": tab['id']});
however, when I send a message to this tab id it doesnt work.
here is the content.js script, but it doesn't alert or console log
chrome.runtime.onMessage.addListener(
async function(request, sender, sendResponse) {
if( request.message === "sendMessage"){
console.log("XX");
alert("XX");
}
}
);
Upvotes: 1
Views: 1407
Reputation: 4683
Got the same issue but I went down the path as @Robbi would approach it above (without the timeout/sleep/delay hack ;) ):
const tabLoadingTrap = { tabId: undefined, resolve: undefined };
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (tabId === tabLoadingTrap.tabId && changeInfo.status === 'complete') {
tabLoadingTrap.resolve();
Object.assign(tabLoadingTrap, { tabId: undefined, resolve: undefined });
}
});
(async () => {
const tab = await chrome.tabs.create({ url: 'https://example.com' });
await waitForTabLoadingToComplete(tab.id);
const response = await chrome.tabs.sendMessage(tab.id, { greeting: 'hello' });
console.log(response);
})();
function waitForTabLoadingToComplete(tabId) {
tabLoadingTrap.tabId = tabId;
return new Promise((resolve) => {
tabLoadingTrap.resolve = resolve;
});
}
Upvotes: 1
Reputation: 6324
adding a setTimeout to call the send function works correctly, just have to have the page load and timer called perfectly, about 8 to 10 seconds is enough time for the page to load.
TIA
Upvotes: 1