Chrome 打开包含网址的标签页
Chrome open tab containing url
我有一个回调函数,它应该在所有选项卡中搜索给定的URL,如果它已打开,则导航到该选项卡,如果未打开,则应打开它。
我有以下查询检查 url 的选项卡
chrome.tabs.query({url: destination}, function (result) {
//If it found no results then the page is not open
if(result == null) {
console.log(destination + " not found in tabs. Function will open Tab.")
//Appropriate function...
}
//If it's open, the function will switch to the tab instead.
else {
//Use the tab ID of the first result
var tabID = result[0].id;
//Appropriate function using id to open tab
}
问题是结果总是 null 或未定义,并且从不返回数组(即使目标 == "http://*/*"( 我最初有 if (result.length == 0(,但它会给出与类型相关的错误
我也尝试过使用
chrome.tabs.update(tabID, {
selected: true
});
切换到选项卡,但这不起作用。我想这可能是因为我需要将其放置在后台.js页面中,但我无法从此页面调用它。
chrome.extension.getBackgroundPage().myFunction();
不起作用。
编辑:
您提到了导致空字符串的权限。这可能是答案,但我确实在权限中设置了选项卡。这些是我在清单中的权限:
"permissions": [
"storage",
"notifications",
"activeTab",
"tabs",
"bookmarks",
"browsingData",
"identity",
"topSites",
"history"
]
这本质上是一个关于chrome.tabs.query的问题。
此方法将对象作为第一个参数。可以使用以下模式之一将名为"url"的属性设置为字符串。结果将是一个数组,其中包含所有选项卡,其 url 与模式匹配。
注意:除非您在清单中指定了"选项卡"权限,或者指定了与返回的 url 值匹配的域,否则任何返回的 TabObject 的 url 属性都将是空字符串。
示例查询:
*://*/* 将返回所有选项卡
http://*/* 将返回所有带有 HTTP 协议的选项卡
http://www.google.com/* 将返回带有 http 协议和域的所有选项卡 www.google.com
虽然这些模式可能会让您想起正则表达式,但它们并不相同。此查询中的最后一个星号始终表示出现 0+。
请注意,您不能使用模式 *://*.google.com/* 搜索 google.com 的所有子域。
我还要在这里指出,您可以为 url 属性提供一组模式以进行搜索。
下面是一个示例:
chrome.tabs.query( { "url":[
"*://music.google.com/*", // copy this from manifest.json is better idea
"*://video.google.com/*"
] }, function( tabs ){
if( tabs.length ){ /* tabs[ 0 ].url is blank depending on permissions */ }
} )