从内容脚本打开 chrome 标签
open a chrome tab from content script
我需要使用内容脚本打开 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
放在一个不会在页面加载时立即 运行 的函数中。
问题很可能是您多次调用 "chrome.runtime.onMessage.addListener",因此当它确实收到消息时,您添加的所有侦听器都会打开一个选项卡,每个已设置一次。
我需要使用内容脚本打开 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
放在一个不会在页面加载时立即 运行 的函数中。
问题很可能是您多次调用 "chrome.runtime.onMessage.addListener",因此当它确实收到消息时,您添加的所有侦听器都会打开一个选项卡,每个已设置一次。