tab.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. /*******************************************************************************
  2. ηMatrix - a browser extension to black/white list requests.
  3. Copyright (C) 2014-2019 Raymond Hill
  4. Copyright (C) 2019-2022 Alessio Vanni
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see {http://www.gnu.org/licenses/}.
  15. Home: https://gitlab.com/vannilla/ematrix
  16. uMatrix Home: https://github.com/gorhill/uMatrix
  17. */
  18. (function () {
  19. 'use strict';
  20. Cu.import('chrome://ematrix/content/lib/UriTools.jsm');
  21. var ηm = ηMatrix;
  22. // https://github.com/gorhill/httpswitchboard/issues/303
  23. // Some kind of trick going on here:
  24. // Any scheme other than 'http' and 'https' is remapped into a
  25. // fake URL which trick the rest of ηMatrix into being able to
  26. // process an otherwise unmanageable scheme. ηMatrix needs web
  27. // page to have a proper hostname to work properly, so just like
  28. // the 'behind-the-scene' fake domain name, we map unknown
  29. // schemes into a fake '{scheme}-scheme' hostname. This way, for
  30. // a specific scheme you can create scope with rules which will
  31. // apply only to that scheme.
  32. ηm.normalizePageURL = function (tabId, pageURL) {
  33. if (vAPI.isBehindTheSceneTabId(tabId)) {
  34. return 'http://' + this.behindTheSceneScope + '/';
  35. }
  36. // https://github.com/gorhill/uMatrix/issues/992
  37. if (pageURL.startsWith('wyciwyg:')) {
  38. // Matches strings like 'wyciwyg://101/'
  39. let filter = /^wyciwyg:\/\/\d+\//.exec(pageURL);
  40. if (filter) {
  41. pageURL = pageURL.slice(filter[0].length);
  42. }
  43. }
  44. // If the URL is that of our "blocked page" document, return
  45. // the URL of the blocked page.
  46. if (pageURL.lastIndexOf(vAPI.getURL('main-blocked.html'), 0) === 0) {
  47. let matches = /main-blocked\.html\?details=([^&]+)/.exec(pageURL);
  48. if (matches && matches.length === 2) {
  49. try {
  50. let details = JSON.parse(atob(matches[1]));
  51. pageURL = details.url;
  52. } catch (e) {
  53. }
  54. }
  55. }
  56. let uri = UriTools.set(pageURL);
  57. let scheme = uri.scheme;
  58. if (scheme === 'https' || scheme === 'http') {
  59. return UriTools.normalizedURI();
  60. }
  61. let fakeHostname = scheme + '-scheme';
  62. if (uri.hostname !== '') {
  63. fakeHostname = uri.hostname + '.' + fakeHostname;
  64. } else if (scheme === 'about') {
  65. fakeHostname = uri.path + '.' + fakeHostname;
  66. }
  67. return 'http://' + fakeHostname + '/';
  68. };
  69. /*
  70. To keep track from which context *exactly* network requests are
  71. made. This is often tricky for various reasons, and the
  72. challenge is not specific to one browser.
  73. The time at which a URL is assigned to a tab and the time when a
  74. network request for a root document is made must be assumed to
  75. be unrelated: it's all asynchronous. There is no guaranteed
  76. order in which the two events are fired.
  77. Also, other "anomalies" can occur:
  78. - a network request for a root document is fired without the
  79. corresponding tab being really assigned a new URL.
  80. <https://github.com/chrisaljoudi/uBlock/issues/516>
  81. - a network request for a secondary resource is labeled with a
  82. tab id for which no root document was pulled for that tab.
  83. <https://github.com/chrisaljoudi/uBlock/issues/1001>
  84. - a network request for a secondary resource is made without the
  85. root document to which it belongs being formally bound yet to
  86. the proper tab id, causing a bad scope to be used for filtering
  87. purpose.
  88. <https://github.com/chrisaljoudi/uBlock/issues/1205>
  89. <https://github.com/chrisaljoudi/uBlock/issues/1140>
  90. So the solution here is to keep a lightweight data structure
  91. which only purpose is to keep track as accurately as possible of
  92. which root document belongs to which tab. That's the only
  93. purpose, and because of this, there are no restrictions for when
  94. the URL of a root document can be associated to a tab.
  95. Before, the PageStore object was trying to deal with this, but
  96. it had to enforce some restrictions so as to not descend into
  97. one of the above issues, or other issues. The PageStore object
  98. can only be associated with a tab for which a definitive
  99. navigation event occurred, because it collects information about
  100. what occurred in the tab (for example, the number of requests
  101. blocked for a page).
  102. The TabContext objects do not suffer this restriction, and as a
  103. result they offer the most reliable picture of which root
  104. document URL is really associated to which tab. Moreover, the
  105. TabObject can undo an association from a root document, and
  106. automatically re-associate with the next most recent. This takes
  107. care of <https://github.com/chrisaljoudi/uBlock/issues/516>.
  108. The PageStore object no longer cache the various information
  109. about which root document it is currently bound. When it needs
  110. to find out, it will always defer to the TabContext object,
  111. which will provide the real answer. This takes case of
  112. <https://github.com/chrisaljoudi/uBlock/issues/1205>. In effect,
  113. the master switch and dynamic filtering rules can be evaluated
  114. now properly even in the absence of a PageStore object, this was
  115. not the case before.
  116. Also, the TabContext object will try its best to find a good
  117. candidate root document URL for when none exists. This takes
  118. care of <https://github.com/chrisaljoudi/uBlock/issues/1001>.
  119. The TabContext manager is self-contained, and it takes care to
  120. properly housekeep itself.
  121. */
  122. ηm.tabContextManager = (function () {
  123. let tabContexts = Object.create(null);
  124. // https://github.com/chrisaljoudi/uBlock/issues/1001
  125. // This is to be used as last-resort fallback in case a tab is
  126. // found to not be bound while network requests are fired for
  127. // the tab.
  128. let mostRecentRootDocURL = '';
  129. let mostRecentRootDocURLTimestamp = 0;
  130. let gcPeriod = 31 * 60 * 1000; // every 31 minutes
  131. // A pushed entry is removed from the stack unless it is
  132. // committed with a set time.
  133. let StackEntry = function (url, commit) {
  134. this.url = url;
  135. this.committed = commit;
  136. this.tstamp = Date.now();
  137. };
  138. let TabContext = function (tabId) {
  139. this.tabId = tabId;
  140. this.stack = [];
  141. this.rawURL =
  142. this.normalURL =
  143. this.scheme =
  144. this.rootHostname =
  145. this.rootDomain = '';
  146. this.secure = false;
  147. this.commitTimer = null;
  148. this.gcTimer = null;
  149. tabContexts[tabId] = this;
  150. };
  151. TabContext.prototype.destroy = function () {
  152. if (vAPI.isBehindTheSceneTabId(this.tabId)) {
  153. return;
  154. }
  155. if (this.gcTimer !== null) {
  156. clearTimeout(this.gcTimer);
  157. this.gcTimer = null;
  158. }
  159. delete tabContexts[this.tabId];
  160. };
  161. TabContext.prototype.onTab = function (tab) {
  162. if (tab) {
  163. this.gcTimer = vAPI.setTimeout(this.onGC.bind(this), gcPeriod);
  164. } else {
  165. this.destroy();
  166. }
  167. };
  168. TabContext.prototype.onGC = function () {
  169. this.gcTimer = null;
  170. if (vAPI.isBehindTheSceneTabId(this.tabId)) {
  171. return;
  172. }
  173. vAPI.tabs.get(this.tabId, this.onTab.bind(this));
  174. };
  175. // https://github.com/gorhill/uBlock/issues/248
  176. // Stack entries have to be committed to stick. Non-committed
  177. // stack entries are removed after a set delay.
  178. TabContext.prototype.onCommit = function () {
  179. if (vAPI.isBehindTheSceneTabId(this.tabId)) {
  180. return;
  181. }
  182. this.commitTimer = null;
  183. // Remove uncommitted entries at the top of the stack.
  184. let i = this.stack.length;
  185. while (i--) {
  186. if (this.stack[i].committed) {
  187. break;
  188. }
  189. }
  190. // https://github.com/gorhill/uBlock/issues/300
  191. // If no committed entry was found, fall back on the bottom-most one
  192. // as being the committed one by default.
  193. if (i === -1 && this.stack.length !== 0) {
  194. this.stack[0].committed = true;
  195. i = 0;
  196. }
  197. ++i;
  198. if (i < this.stack.length) {
  199. this.stack.length = i;
  200. this.update();
  201. ηm.bindTabToPageStats(this.tabId, 'newURL');
  202. }
  203. };
  204. // This takes care of orphanized tab contexts. Can't be
  205. // started for all contexts, as the behind-the-scene context
  206. // is permanent -- so we do not want to flush it.
  207. TabContext.prototype.autodestroy = function () {
  208. if (vAPI.isBehindTheSceneTabId(this.tabId)) {
  209. return;
  210. }
  211. this.gcTimer = vAPI.setTimeout(this.onGC.bind(this), gcPeriod);
  212. };
  213. // Update just force all properties to be updated to match the
  214. // most recent root URL.
  215. TabContext.prototype.update = function () {
  216. if (this.stack.length === 0) {
  217. this.rawURL =
  218. this.normalURL =
  219. this.scheme =
  220. this.rootHostname =
  221. this.rootDomain = '';
  222. this.secure = false;
  223. return;
  224. }
  225. this.rawURL = this.stack[this.stack.length - 1].url;
  226. this.normalURL = ηm.normalizePageURL(this.tabId, this.rawURL);
  227. this.scheme = UriTools.schemeFromURI(this.rawURL);
  228. this.rootHostname = UriTools.hostnameFromURI(this.normalURL);
  229. this.rootDomain = UriTools.domainFromHostname(this.rootHostname)
  230. || this.rootHostname;
  231. this.secure = UriTools.isSecureScheme(this.scheme);
  232. };
  233. // Called whenever a candidate root URL is spotted for the tab.
  234. TabContext.prototype.push = function (url, context) {
  235. if (vAPI.isBehindTheSceneTabId(this.tabId)) {
  236. return;
  237. }
  238. let committed = context !== undefined;
  239. let count = this.stack.length;
  240. let topEntry = this.stack[count - 1];
  241. if (topEntry && topEntry.url === url) {
  242. if (committed) {
  243. topEntry.committed = true;
  244. }
  245. return;
  246. }
  247. if (this.commitTimer !== null) {
  248. clearTimeout(this.commitTimer);
  249. }
  250. if (committed) {
  251. this.stack = [new StackEntry(url, true)];
  252. } else {
  253. this.stack.push(new StackEntry(url));
  254. this.commitTimer =
  255. vAPI.setTimeout(this.onCommit.bind(this), 1000);
  256. }
  257. this.update();
  258. ηm.bindTabToPageStats(this.tabId, context);
  259. };
  260. // These are to be used for the API of the tab context manager.
  261. let push = function (tabId, url, context) {
  262. let entry = tabContexts[tabId];
  263. if (entry === undefined) {
  264. entry = new TabContext(tabId);
  265. entry.autodestroy();
  266. }
  267. entry.push(url, context);
  268. mostRecentRootDocURL = url;
  269. mostRecentRootDocURLTimestamp = Date.now();
  270. return entry;
  271. };
  272. // Find a tab context for a specific tab. If none is found,
  273. // attempt to fix this. When all fail, the behind-the-scene
  274. // context is returned.
  275. let mustLookup = function (tabId, url) {
  276. let entry;
  277. if (url !== undefined) {
  278. entry = push(tabId, url);
  279. } else {
  280. entry = tabContexts[tabId];
  281. }
  282. if (entry !== undefined) {
  283. return entry;
  284. }
  285. // https://github.com/chrisaljoudi/uBlock/issues/1025
  286. // Google Hangout popup opens without a root frame. So for
  287. // now we will just discard that best-guess root frame if
  288. // it is too far in the future, at which point it ceases
  289. // to be a "best guess".
  290. if (mostRecentRootDocURL
  291. !== '' && mostRecentRootDocURLTimestamp + 500 < Date.now()) {
  292. mostRecentRootDocURL = '';
  293. }
  294. // https://github.com/chrisaljoudi/uBlock/issues/1001
  295. // Not a behind-the-scene request, yet no page store found
  296. // for the tab id: we will thus bind the last-seen root
  297. // document to the unbound tab. It's a guess, but better
  298. // than ending up filtering nothing at all.
  299. if (mostRecentRootDocURL !== '') {
  300. return push(tabId, mostRecentRootDocURL);
  301. }
  302. // If all else fail at finding a page store, re-categorize
  303. // the request as behind-the-scene. At least this ensures
  304. // that ultimately the user can still inspect/filter those
  305. // net requests which were about to fall through the
  306. // cracks.
  307. // Example: Chromium + case #12 at
  308. // http://raymondhill.net/ublock/popup.html
  309. return tabContexts[vAPI.noTabId];
  310. };
  311. let lookup = function (tabId) {
  312. return tabContexts[tabId] || null;
  313. };
  314. // Behind-the-scene tab context
  315. (function () {
  316. let entry = new TabContext(vAPI.noTabId);
  317. entry.stack.push(new StackEntry('', true));
  318. entry.rawURL = '';
  319. entry.normalURL = ηm.normalizePageURL(entry.tabId);
  320. entry.rootHostname = UriTools.hostnameFromURI(entry.normalURL);
  321. entry.rootDomain = UriTools.domainFromHostname(entry.rootHostname)
  322. || entry.rootHostname;
  323. })();
  324. // https://github.com/gorhill/uMatrix/issues/513
  325. // Force a badge update here, it could happen that all the
  326. // subsequent network requests are already in the page
  327. // store, which would cause the badge to no be updated for
  328. // these network requests.
  329. vAPI.tabs.onNavigation = function (details) {
  330. let tabId = details.tabId;
  331. if (vAPI.isBehindTheSceneTabId(tabId)) {
  332. return;
  333. }
  334. push(tabId, details.url, 'newURL');
  335. ηm.updateBadgeAsync(tabId);
  336. };
  337. // https://github.com/gorhill/uMatrix/issues/872
  338. // `changeInfo.url` may not always be available (Firefox).
  339. vAPI.tabs.onUpdated = function (tabId, changeInfo, tab) {
  340. if (vAPI.isBehindTheSceneTabId(tabId)) {
  341. return;
  342. }
  343. if (typeof tab.url !== 'string' || tab.url === '') {
  344. return;
  345. }
  346. let url = changeInfo.url || tab.url;
  347. if (url) {
  348. push(tabId, url, 'updateURL');
  349. }
  350. };
  351. vAPI.tabs.onClosed = function (tabId) {
  352. ηm.unbindTabFromPageStats(tabId);
  353. let entry = tabContexts[tabId];
  354. if (entry instanceof TabContext) {
  355. entry.destroy();
  356. }
  357. };
  358. return {
  359. push: push,
  360. lookup: lookup,
  361. mustLookup: mustLookup
  362. };
  363. })();
  364. vAPI.tabs.registerListeners();
  365. // Create an entry for the tab if it doesn't exist
  366. ηm.bindTabToPageStats = function (tabId, context) {
  367. this.updateBadgeAsync(tabId);
  368. // Do not create a page store for URLs which are of no
  369. // interests Example: dev console
  370. let tabContext = this.tabContextManager.lookup(tabId);
  371. if (tabContext === null) {
  372. throw new Error('Unmanaged tab id: ' + tabId);
  373. }
  374. // rhill 2013-11-24: Never ever rebind behind-the-scene
  375. // virtual tab.
  376. // https://github.com/gorhill/httpswitchboard/issues/67
  377. if (vAPI.isBehindTheSceneTabId(tabId)) {
  378. return this.pageStores[tabId];
  379. }
  380. let normalURL = tabContext.normalURL;
  381. let pageStore = this.pageStores[tabId] || null;
  382. // The previous page URL, if any, associated with the tab
  383. if (pageStore !== null) {
  384. // No change, do not rebind
  385. if (pageStore.pageUrl === normalURL) {
  386. return pageStore;
  387. }
  388. // https://github.com/gorhill/uMatrix/issues/37
  389. // Just rebind whenever possible: the URL changed, but the
  390. // document maybe is the same.
  391. // Example: Google Maps, Github
  392. // https://github.com/gorhill/uMatrix/issues/72
  393. // Need to double-check that the new scope is same as old scope
  394. if (context === 'updateURL'
  395. && pageStore.pageHostname === tabContext.rootHostname) {
  396. pageStore.rawURL = tabContext.rawURL;
  397. pageStore.normalURL = normalURL;
  398. this.updateTitle(tabId);
  399. this.pageStoresToken = Date.now();
  400. return pageStore;
  401. }
  402. // We won't be reusing this page store.
  403. this.unbindTabFromPageStats(tabId);
  404. }
  405. // Try to resurrect first.
  406. pageStore = this.resurrectPageStore(tabId, normalURL);
  407. if (pageStore === null) {
  408. pageStore = this.pageStoreFactory(tabContext);
  409. }
  410. this.pageStores[tabId] = pageStore;
  411. this.updateTitle(tabId);
  412. this.pageStoresToken = Date.now();
  413. return pageStore;
  414. };
  415. ηm.unbindTabFromPageStats = function (tabId) {
  416. if (vAPI.isBehindTheSceneTabId(tabId)) {
  417. return;
  418. }
  419. let pageStore = this.pageStores[tabId] || null;
  420. if (pageStore === null) {
  421. return;
  422. }
  423. delete this.pageStores[tabId];
  424. this.pageStoresToken = Date.now();
  425. if (pageStore.incinerationTimer) {
  426. clearTimeout(pageStore.incinerationTimer);
  427. pageStore.incinerationTimer = null;
  428. }
  429. if (this.pageStoreCemetery.hasOwnProperty(tabId) === false) {
  430. this.pageStoreCemetery[tabId] = {};
  431. }
  432. let pageStoreCrypt = this.pageStoreCemetery[tabId];
  433. let pageURL = pageStore.pageUrl;
  434. pageStoreCrypt[pageURL] = pageStore;
  435. pageStore.incinerationTimer =
  436. vAPI.setTimeout(this.incineratePageStore.bind(this, tabId, pageURL),
  437. 4 * 60 * 1000);
  438. };
  439. ηm.resurrectPageStore = function (tabId, pageURL) {
  440. if (this.pageStoreCemetery.hasOwnProperty(tabId) === false) {
  441. return null;
  442. }
  443. let pageStoreCrypt = this.pageStoreCemetery[tabId];
  444. if (pageStoreCrypt.hasOwnProperty(pageURL) === false) {
  445. return null;
  446. }
  447. let pageStore = pageStoreCrypt[pageURL];
  448. if (pageStore.incinerationTimer !== null) {
  449. clearTimeout(pageStore.incinerationTimer);
  450. pageStore.incinerationTimer = null;
  451. }
  452. delete pageStoreCrypt[pageURL];
  453. if (Object.keys(pageStoreCrypt).length === 0) {
  454. delete this.pageStoreCemetery[tabId];
  455. }
  456. return pageStore;
  457. };
  458. ηm.incineratePageStore = function (tabId, pageURL) {
  459. if (this.pageStoreCemetery.hasOwnProperty(tabId) === false) {
  460. return;
  461. }
  462. let pageStoreCrypt = this.pageStoreCemetery[tabId];
  463. if (pageStoreCrypt.hasOwnProperty(pageURL) === false) {
  464. return;
  465. }
  466. let pageStore = pageStoreCrypt[pageURL];
  467. if (pageStore.incinerationTimer !== null) {
  468. clearTimeout(pageStore.incinerationTimer);
  469. pageStore.incinerationTimer = null;
  470. }
  471. delete pageStoreCrypt[pageURL];
  472. if (Object.keys(pageStoreCrypt).length === 0) {
  473. delete this.pageStoreCemetery[tabId];
  474. }
  475. pageStore.dispose();
  476. };
  477. ηm.pageStoreFromTabId = function (tabId) {
  478. return this.pageStores[tabId] || null;
  479. };
  480. // Never return null
  481. ηm.mustPageStoreFromTabId = function (tabId) {
  482. return this.pageStores[tabId] || this.pageStores[vAPI.noTabId];
  483. };
  484. ηm.forceReload = function (tabId, bypassCache) {
  485. vAPI.tabs.reload(tabId, bypassCache);
  486. };
  487. // Update badge
  488. // rhill 2013-11-09: well this sucks, I can't update icon/badge
  489. // incrementally, as chromium overwrite the icon at some point
  490. // without notifying me, and this causes internal cached state to
  491. // be out of sync.
  492. // ηMatrix: does it matter to us?
  493. ηm.updateBadgeAsync = (function () {
  494. let tabIdToTimer = Object.create(null);
  495. let updateBadge = function (tabId) {
  496. delete tabIdToTimer[tabId];
  497. let iconId = null;
  498. let badgeStr = '';
  499. let pageStore = this.pageStoreFromTabId(tabId);
  500. if (pageStore !== null) {
  501. let total = pageStore.perLoadAllowedRequestCount +
  502. pageStore.perLoadBlockedRequestCount;
  503. if (total) {
  504. let squareSize = 19;
  505. let greenSize = squareSize *
  506. Math.sqrt(pageStore.perLoadAllowedRequestCount / total);
  507. iconId = greenSize < squareSize/2 ?
  508. Math.ceil(greenSize) :
  509. Math.floor(greenSize);
  510. }
  511. if (this.userSettings.iconBadgeEnabled
  512. && pageStore.perLoadBlockedRequestCount !== 0) {
  513. badgeStr =
  514. this.formatCount(pageStore.perLoadBlockedRequestCount);
  515. }
  516. }
  517. vAPI.setIcon(tabId, iconId, badgeStr);
  518. };
  519. return function (tabId) {
  520. if (tabIdToTimer[tabId]) {
  521. return;
  522. }
  523. if (vAPI.isBehindTheSceneTabId(tabId)) {
  524. return;
  525. }
  526. tabIdToTimer[tabId] =
  527. vAPI.setTimeout(updateBadge.bind(this, tabId), 750);
  528. };
  529. })();
  530. ηm.updateTitle = (function () {
  531. let tabIdToTimer = Object.create(null);
  532. let tabIdToTryCount = Object.create(null);
  533. let delay = 499;
  534. let tryNoMore = function (tabId) {
  535. delete tabIdToTryCount[tabId];
  536. };
  537. let tryAgain = function (tabId) {
  538. let count = tabIdToTryCount[tabId];
  539. if (count === undefined) {
  540. return false;
  541. }
  542. if (count === 1) {
  543. delete tabIdToTryCount[tabId];
  544. return false;
  545. }
  546. tabIdToTryCount[tabId] = count - 1;
  547. tabIdToTimer[tabId] =
  548. vAPI.setTimeout(updateTitle.bind(ηm, tabId), delay);
  549. return true;
  550. };
  551. let onTabReady = function (tabId, tab) {
  552. if (!tab) {
  553. return tryNoMore(tabId);
  554. }
  555. let pageStore = this.pageStoreFromTabId(tabId);
  556. if (pageStore === null) {
  557. return tryNoMore(tabId);
  558. }
  559. if (!tab.title && tryAgain(tabId)) {
  560. return;
  561. }
  562. // https://github.com/gorhill/uMatrix/issues/225
  563. // Sometimes title changes while page is loading.
  564. let settled = tab.title && tab.title === pageStore.title;
  565. pageStore.title = tab.title || tab.url || '';
  566. this.pageStoresToken = Date.now();
  567. if (settled || !tryAgain(tabId)) {
  568. tryNoMore(tabId);
  569. }
  570. };
  571. let updateTitle = function (tabId) {
  572. delete tabIdToTimer[tabId];
  573. vAPI.tabs.get(tabId, onTabReady.bind(this, tabId));
  574. };
  575. return function (tabId) {
  576. if (vAPI.isBehindTheSceneTabId(tabId)) {
  577. return;
  578. }
  579. if (tabIdToTimer[tabId]) {
  580. clearTimeout(tabIdToTimer[tabId]);
  581. }
  582. tabIdToTimer[tabId] =
  583. vAPI.setTimeout(updateTitle.bind(this, tabId), delay);
  584. tabIdToTryCount[tabId] = 5;
  585. };
  586. })();
  587. // Stale page store entries janitor
  588. // https://github.com/chrisaljoudi/uBlock/issues/455
  589. (function () {
  590. let cleanupPeriod = 7 * 60 * 1000;
  591. let cleanupSampleAt = 0;
  592. let cleanupSampleSize = 11;
  593. let cleanup = function () {
  594. let tabIds = Object.keys(ηm.pageStores).sort();
  595. let checkTab = function(tabId) {
  596. vAPI.tabs.get(tabId, function (tab) {
  597. if (!tab) {
  598. ηm.unbindTabFromPageStats(tabId);
  599. }
  600. });
  601. };
  602. if (cleanupSampleAt >= tabIds.length) {
  603. cleanupSampleAt = 0;
  604. }
  605. let tabId;
  606. let n =
  607. Math.min(cleanupSampleAt + cleanupSampleSize, tabIds.length);
  608. for (let i=cleanupSampleAt; i<n; i++) {
  609. tabId = tabIds[i];
  610. if (vAPI.isBehindTheSceneTabId(tabId)) {
  611. continue;
  612. }
  613. checkTab(tabId);
  614. }
  615. cleanupSampleAt = n;
  616. vAPI.setTimeout(cleanup, cleanupPeriod);
  617. };
  618. vAPI.setTimeout(cleanup, cleanupPeriod);
  619. })();
  620. })();