[英]Change Active Window (chrome.tabs)
I've made an extension for pandora.com
and when the user clicks the extension icon it opens a new tab with pandora.我已经为
pandora.com
做了一个扩展,当用户点击扩展图标时,它会打开一个带有 Pandora 的新标签。
When pandora is already open in a new tab and the user clicks the extension, the extension will not open a new tab but I would like it to instead change the active tab to the tab with pandora already open.当潘多拉已经在新标签中打开并且用户单击扩展时,扩展不会打开新标签,但我希望它改为将活动标签更改为潘多拉已经打开的标签。
This is what I have so far in my background
page:这是我迄今为止在我的
background
页面中的内容:
chrome.browserAction.onClicked.addListener(function(tab) {
var found = false;
chrome.tabs.query({}, function (tabs) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].url.search("pandora.com") > -1){
found= true;
}
}
if (found==false){
chrome.tabs.executeScript(null,{file: "buy.js"});
} else {
// Changes active tab to the tab with pandora open
}
});
});
UPDATE- chrome.tabs.update(tabId, {selected: true});
更新-
chrome.tabs.update(tabId, {selected: true});
achieves what I needed.实现了我所需要的。 Here's the final code:
这是最终的代码:
chrome.browserAction.onClicked.addListener(function(tab) {
var found = false;
var tabId;
chrome.tabs.query({}, function (tabs) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].url.search("www.pandora.com/") > -1){
found = true;
tabId = tabs[i].id;
}
}
if (found == false){
chrome.tabs.executeScript(null,{file: "buy.js"});
} else {
chrome.tabs.update(tabId, {selected: true});
}
});
});
Seems like the selected
property of the second argument of chrome.tabs.update
has now been deprecated.似乎
chrome.tabs.update
的第二个参数的selected
属性现在已被弃用。
Using the active
property is the new way to do it:使用
active
属性是一种新的方法:
chrome.tabs.update(tabId, {active: true})
If the tab to be activated is in another window, you also need to change the active window to that window using chrome.windows.update
:如果要激活的选项卡在另一个窗口中,您还需要使用
chrome.windows.update
将活动窗口更改为该窗口:
chrome.windows.update(windowId, {focused: true}, (window) => {
chrome.tabs.update(tabId, {active: true})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.