如何使用 chrome.windows.create 将消息发送到新创建的 window 选项卡

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

我通过扩展程序创建了一个新的 chrome window 选项卡,但我无法向其内容脚本发送消息,事件从未触发

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
    }
});

逻辑似乎是正确的,但可能 sendMessage 之前被调用 content_script.js 是 运行。

要验证这一点,请在 sendMessage 行之前使用 console.log(new Date) 并在内容脚本中使用另一个。然后您可以比较日期。

如果这是问题所在,您可以让内容脚本在加载时向后台脚本发送消息,这样就没有竞争条件。