从内容脚本打开chrome选项卡

open a chrome tab from content script

本文关键字:chrome 选项 脚本      更新时间:2024-03-20

我需要使用内容脚本打开一个chrome选项卡。我检查了chrome示例中的消息传递,并尝试了此操作
在内容脚本中:

chrome.runtime.sendMessage({greeting: "hello"}, function (response) {
    console.log(response.farewell);
});

在后台.js

chrome.runtime.onMessage.addListener(
        function (request, sender, sendResponse) {
            chrome.extension.getBackgroundPage().console.log('resp.type');
            console.log(sender.tab ?
                    "from a content script:" + sender.tab.url :
                    "from the extension");
            if (request.greeting == "hello") {
                chrome.tabs.create({url: 'http://google.com'});
                sendResponse({farewell: "goodbye"});
            }
        });

它工作得很好,问题是选项卡正在打开,但也有很多选项卡被打开。。。我需要做什么才能只打开一个选项卡?

当您运行内容脚本时,它也会在您打开的新选项卡中运行,因此它最终会打开无限多的选项卡。为了限制这种情况,可以将tabs.create放在页面加载时不会立即运行的函数中。

问题很可能是您多次调用"chrome.runtime.onMessage.addListener",因此当它收到消息时,您添加的所有侦听器都会打开一个选项卡,每个选项卡都会打开。