最好的方法来检查Tab是否与确切的ID存在于Chrome
The best way to check if Tab with exact ID exists in Chrome
有时选项卡Id存储在变量中,您需要在对其进行操作之前检查选项卡是否仍然存在(因为用户可以随时关闭选项卡)。我找到了这个解决方案:
chrome.tabs.get(1234567, function(tab) {
if (typeof tab == 'undefined') {
console.log('Tab does not exist!');
}
});
它可以工作,但它有相当严重的缺点。它像这样将错误信息写入控制台:
Error during tabs.get: No tab with id: 1234567.
这也不例外。所以try/catch帮不上忙。这只是控制台的一条消息。
任何想法?
UPDATE:这个错误现在看起来像
Unchecked runtime.lastError while running tabs.get: No tab with id: 1234567.
function callback() {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError.message);
} else {
// Tab exists
}
}
chrome.tabs.get(1234,callback);
source Chrome扩展错误:"未检查运行时。运行browserAction时发生错误。setIcon:没有id"
编辑:Chrome检查是否检入了Chrome .runtime. lasterror的值回调,并为此"未处理的异步"输出控制台消息例外"。如果你检查它,它不会污染控制台。
来自@Xan的评论
根据Ian的评论(谢谢@Ian)有另一个解决方案。
function tabExists (tabId, onExists, onNotExists) {
chrome.windows.getAll({ populate: true }, function (windows) {
for (var i = 0, window; window = windows[i]; i++) {
for (var j = 0, tab; tab = window.tabs[j]; j++) {
if (tab.id == tabId) {
onExists && onExists(tab);
return;
}
}
}
onNotExists && onNotExists();
});
}
它经过测试并且工作良好,所以每个人都可以使用它。如果有人能找到比chrome.windows.getAll
更短的解决方案,请写信!
更新:由于@anglinb的答案这个我的答案是不实际的了
我很惊讶竟然没有API来完成这个简单的任务。除了@KonstantinSmolyanin上面的建议,我想出了这个更简单的方法:
function checkTabIDValid(nTabID, callbackDone)
{
chrome.browserAction.getBadgeText({tabId: nTabID}, function(dummy)
{
if(callbackDone)
callbackDone(!chrome.runtime.lastError);
});
}
不幸的是,它还必须异步报告结果:
checkTabIDValid(tabId, function(res){
console.log("tab " + (res ? "exists" : "doesn't exist"));
});
实际上,在chrome API中没有"exists"函数…我写了下面的代码:
var tabID = 551;
chrome.tabs.query( {}, function(tabs) {
for(let i = 0; i<tabs.length; i++){
if (tabs[i].id === tabID) {
alert(`Tab ${tabID} exists!`);
return;
}
}
alert(`No Tab ${tabID} here.`);
});
在
前面设置一个变量lastRemoved=tab.id;
chrome.tabs.remove(tab.id);
在
后面检查chrome.tabs.onUpdated.addListener(function(tabId){
if(lastRemoved==tabId) return;
chrome.tabs.get(tabId,
//...
相关文章:
- 在Chrome for iOS中,附加到用户代理字符串的唯一选项卡ID
- Chrome扩展插件:runtime.last运行tabs.get/tabs.remove时出错:没有id为0的选项卡
- Chrome 提前更改 HTML ID
- Chrome 标签页的永久唯一 ID,在浏览器会话之间持续存在
- 无法让 .focus() 专注于 Chrome、Safari 和 FF 中带有 id 的输入
- 在Chrome中,只需键入元素的ID即可自动选择它
- $(“#id选项”).hide();不适用于safari/chrome
- Chrome应用程序-标识API-错误的客户端ID NON_NAME
- $(“#id option”).click(function(){ }) 不适用于 safari 或 chrome
- 如何动态地将chrome扩展ID发送到网页以进行消息传递
- Google Chrome不允许我使用ID的setAttribute;s
- 标签ID和根URL是否会从Google Chrome扩展的内容脚本中更改
- 如何将OAuth2客户端id与chrome扩展文件一起分发
- Chrome同步文件系统和应用程序ID
- 如何在Chrome扩展中验证选项卡id
- Chrome扩展错误:“;未选中runtime.last运行browserAction.setIcon时出错:没有id为
- chrome扩展弹出无法找到元素的ID
- event.target.id仅在Chrome中工作
- Chrome -查找iframe的frameId(不是id属性)
- chrome.identity.getAuthToken返回"错误的客户端id:{0}”;错误