Search code examples
javascriptgoogle-chrome-extension

How to send message to newly created window tab using chrome.windows.create


I created a new chrome window tab via extension but I can't send message to its content script, the event never fired

background.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.action == "run") {
        chrome.tabs.create({
            url: 'https://vnexpress.net/',
            active: false
        }, function (tab) {
            chrome.windows.create({
                tabId: tab.id,
                type: 'popup',
                focused: true
            }, function (win) {
                chrome.tabs.sendMessage(win.tabId, { action: "scrape" });
            });
        });
    }

    sendResponse();
})

content_script.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action == "scrape") {
        alert("Scraping!!!");
        console.log("Scraping")
        //This never run
    }
});

Solution

  • The logic seems to be correct, but probably sendMessage is being called before content_script.js is run.

    To verify this, use console.log(new Date) before the sendMessage line and another one in the content script. You can then compare the dates.

    If that's the issue, you could have the content script message the background script when it loads instead, so there's no race condition.