假设我在 Chrome 中打开了一堆选项卡,我关闭浏览器,然后重新打开它。这些选项卡将保持卸载状态,直到我单击它们,然后它们才会自动加载。这是浏览器的原生功能,旨在节省内存。
我正在寻找一种方法来检查选项卡何时处于此特定状态,然后再单击它们。我尝试了 chrome.tabs api 中提到的两个属性 .status 和 .discarded,它们在选项卡被卸载或丢弃时提供信息:
https://developer.chrome.com/docs/extensions/reference/tabs/
但它们赋予这些属性的值始终相同,无论这些选项卡在重新启动后完全卸载还是在我单击它们后完全加载:
.status = "complete"
.discarded = "false"
现在我陷入困境了。我不知道如何解决这个问题。 任何帮助将不胜感激。谢谢你。
ps。我没有使用任何选项卡悬浮插件。
您可以检查选项卡的已放弃或状态属性,已放弃的选项卡将其状态为“已卸载”:
chrome.runtime.onStartup.addListener(()=>{
chrome.tabs.query({currentWindow: true}, (tabs)=>{
tabs.forEach(tab =>{
if(tab.discarded === true || tab.status === “unloaded” ){
//Do something
}
})
})
});
John Yepthomi 的答案并不完全正确,一个选项卡可能会被丢弃并加载,并且可能会同时卸载和不同时丢弃!,这似乎是 chrome 中的一个错误...
以下是这种奇怪行为的一些屏幕截图: 选项卡被卸载并且没有被丢弃!
解决方案是像这样分别检查两种状态(丢弃和卸载),现在按预期工作:
// count the total number of discarded/unloaded tabs in all windows
function getAllStats() {
chrome.windows.getAll({populate: true}, function (window_list) {
let allWindowsTabCount = 0;
let discardedTabsCount = 0;
//count all tabs in all windows
for(var i=0; i<window_list.length; i++) {
allWindowsTabCount += window_list[i].tabs.length; // total number of tabs
for (let tab of window_list[i].tabs) {
// count the total number of discarded tabs
let isDiscarded = false;
if (tab.status === "unloaded") {
isDiscarded = true;
}
if (tab.discarded === true) {
isDiscarded = true;
}
if (isDiscarded === true) {
discardedTabsCount++;
}
}
}
let nonDiscardedTabsCount = allWindowsTabCount - discardedTabsCount;
console.log("nonDiscardedTabsCount is: ", nonDiscardedTabsCount);
console.log("discardedTabsCount is: ", discardedTabsCount);
});
}
getAllStats();