[英]Check if tab exists and make it active; otherwise create it
I'm attempting to see if the tab ' http://google.com ' exists.我正在尝试查看标签“ http://google.com ”是否存在。 If it does then I want to make it the active page.
如果是,那么我想将其设为活动页面。 Otherwise, the tab ' http://google.com ' doesn't exist, and I want to create it.
否则,标签“ http://google.com ”不存在,我想创建它。
backround.js后台.js
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
chrome.tabs.create({'url': 'http://google.com'}, function(tab) {
alert('Tab Created ' + tab.id);
var oms = tab.id;
chrome.tabs.update(oms, {url:"http://en.wikipedia.org"});
});
});
This creates the webpage, gets the tabid
and sets the tabid
as a variable.这将创建网页,获取
tabid
并设置tabid
作为变量。
Your current attempt seems to be trying to create a tab with Google, and then navigate it to Wikipedia.您当前的尝试似乎是尝试使用 Google 创建一个选项卡,然后将其导航到 Wikipedia。 This doesn't agree with your initial paragraph.
这与您的初始段落不一致。 Instead, I think you want something similar to the following:
相反,我认为您需要类似于以下内容的内容:
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
chrome.tabs.query({'url': 'http://google.com'}, function(tabs) {
if ( tabs.length > 0 ) {
chrome.tabs.update(tabs[0].id,{'active':true});
} else {
chrome.tabs.create({'url':'http://google.com'});
}
});
});
Note that this won't find http://www.google.com , or http://google.com/otherstuff .请注意,这不会找到http://www.google.com或http://google.com/otherstuff 。 You'll probably want to use a match pattern .
您可能想要使用匹配模式。
You commented having trouble with updating the tab to be selected
.您评论了更新要
selected
的选项卡时遇到问题。 The documentation says that selected
is deprecated in favor of highlighted
. 文档说
selected
已被弃用,而支持highlighted
。 This also hints what else may have happened: a highlighted
tab is not necessarily active (specifically, you can have several tabs highlighted
).这也暗示了其他可能发生的事情:
highlighted
选项卡不一定处于活动状态(特别是,您可以highlighted
多个选项卡)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.