gpt4 book ai didi

javascript - 从内容脚本打开一个 chrome 选项卡

转载 作者:行者123 更新时间:2023-11-29 15:36:11 25 4
gpt4 key购买 nike

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

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

在 background.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 放在一个不会在页面加载时立即运行的函数中。

关于javascript - 从内容脚本打开一个 chrome 选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28644920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com