Skip to content

Commit f79a267

Browse files
committed
Add URLCache to prevent redundant tab sorting
1 parent 0a3b8f7 commit f79a267

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

background.js

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,37 @@ class Window {
448448
}
449449
}
450450

451+
// The URLCache maps each tab ID to its URL. When a tab is updated, we check
452+
// the URLCache to determine if the URL has changed significantly. If not,
453+
// then we will avoid re-sorting the window.
454+
const urlCache = {
455+
_urls: new Map(),
456+
457+
isTabUrlChanged: function(tab) {
458+
let newUrl = null;
459+
try {
460+
newUrl = new URL(tab.url);
461+
} catch (error) {
462+
// The URL cannot be parsed (could be a local PDF file). Clear
463+
// the tab from the cache and always consider the URL changed.
464+
this._urls.delete(tab.id);
465+
return true;
466+
}
467+
if (this._urls.has(tab.id)) {
468+
const oldUrl = this._urls.get(tab.id);
469+
if (oldUrl.host == newUrl.host && oldUrl.pathname == newUrl.pathname) {
470+
return false;
471+
}
472+
}
473+
this._urls.set(tab.id, newUrl);
474+
return true;
475+
},
476+
477+
removeTab: function(tabId) {
478+
this._urls.delete(tabId);
479+
},
480+
};
481+
451482
// Wrap the service worker logic with an immediately-invoked function expression
452483
// (IIFE). This allows await-ing the results of APIs at the "top-level".
453484
(async () => {
@@ -477,15 +508,20 @@ class Window {
477508

478509
// Register callback when a tab gets updated.
479510
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
480-
if (changeInfo.status == "complete") {
511+
if (("url" in changeInfo || changeInfo.status == "complete") &&
512+
urlCache.isTabUrlChanged(tab)) {
513+
481514
const window = new Window(tab.windowId);
482515
await window.sortAndGroupTabs();
516+
} else {
517+
console.debug("Ignoring tab update:", changeInfo, tab);
483518
}
484519
});
485520

486521
// Register callback when a tab gets closed.
487522
chrome.tabs.onRemoved.addListener(async (tabId, removeInfo) => {
488523
if (!removeInfo.isWindowClosing) {
524+
urlCache.removeTab(tabId);
489525
const window = new Window(removeInfo.windowId);
490526
await window.sortAndGroupTabs();
491527
}

0 commit comments

Comments
 (0)