You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1070 lines
34 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
10 years ago
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
  1. /*******************************************************************************
  2. uMatrix - a browser extension to block requests.
  3. Copyright (C) 2014-2017 The uBlock Origin authors
  4. Copyright (C) 2017 Raymond Hill
  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://github.com/gorhill/uMatrix
  16. */
  17. /* global self, µMatrix */
  18. // For background page
  19. 'use strict';
  20. /******************************************************************************/
  21. (function() {
  22. /******************************************************************************/
  23. var vAPI = self.vAPI = self.vAPI || {};
  24. var chrome = self.chrome;
  25. var manifest = chrome.runtime.getManifest();
  26. vAPI.chrome = true;
  27. vAPI.webextFlavor = '';
  28. if (
  29. self.browser instanceof Object &&
  30. typeof self.browser.runtime.getBrowserInfo === 'function'
  31. ) {
  32. self.browser.runtime.getBrowserInfo().then(function(info) {
  33. vAPI.webextFlavor = info.vendor + '-' + info.name + '-' + info.version;
  34. });
  35. }
  36. var noopFunc = function(){};
  37. /******************************************************************************/
  38. // https://github.com/gorhill/uMatrix/issues/234
  39. // https://developer.chrome.com/extensions/privacy#property-network
  40. chrome.privacy.network.networkPredictionEnabled.set({
  41. value: false
  42. });
  43. /******************************************************************************/
  44. vAPI.app = {
  45. name: manifest.name,
  46. version: manifest.version
  47. };
  48. /******************************************************************************/
  49. vAPI.app.start = function() {
  50. };
  51. /******************************************************************************/
  52. vAPI.app.stop = function() {
  53. };
  54. /******************************************************************************/
  55. vAPI.app.restart = function() {
  56. chrome.runtime.reload();
  57. };
  58. /******************************************************************************/
  59. // chrome.storage.local.get(null, function(bin){ console.debug('%o', bin); });
  60. vAPI.storage = chrome.storage.local;
  61. vAPI.cacheStorage = chrome.storage.local;
  62. /******************************************************************************/
  63. vAPI.tabs = {};
  64. /******************************************************************************/
  65. vAPI.isBehindTheSceneTabId = function(tabId) {
  66. return tabId.toString() === '-1';
  67. };
  68. vAPI.noTabId = '-1';
  69. /******************************************************************************/
  70. vAPI.tabs.registerListeners = function() {
  71. var onNavigationClient = this.onNavigation || noopFunc;
  72. var onUpdatedClient = this.onUpdated || noopFunc;
  73. var onClosedClient = this.onClosed || noopFunc;
  74. // https://developer.chrome.com/extensions/webNavigation
  75. // [onCreatedNavigationTarget ->]
  76. // onBeforeNavigate ->
  77. // onCommitted ->
  78. // onDOMContentLoaded ->
  79. // onCompleted
  80. // The chrome.webRequest.onBeforeRequest() won't be called for everything
  81. // else than `http`/`https`. Thus, in such case, we will bind the tab as
  82. // early as possible in order to increase the likelihood of a context
  83. // properly setup if network requests are fired from within the tab.
  84. // Example: Chromium + case #6 at
  85. // http://raymondhill.net/ublock/popup.html
  86. var reGoodForWebRequestAPI = /^https?:\/\//;
  87. var onCreatedNavigationTarget = function(details) {
  88. //console.debug('onCreatedNavigationTarget: tab id %d = "%s"', details.tabId, details.url);
  89. if ( reGoodForWebRequestAPI.test(details.url) ) {
  90. return;
  91. }
  92. details.tabId = details.tabId.toString();
  93. onNavigationClient(details);
  94. };
  95. var onUpdated = function(tabId, changeInfo, tab) {
  96. tabId = tabId.toString();
  97. onUpdatedClient(tabId, changeInfo, tab);
  98. };
  99. var onCommitted = function(details) {
  100. // Important: do not call client if not top frame.
  101. if ( details.frameId !== 0 ) {
  102. return;
  103. }
  104. details.tabId = details.tabId.toString();
  105. onNavigationClient(details);
  106. //console.debug('onCommitted: tab id %d = "%s"', details.tabId, details.url);
  107. };
  108. var onClosed = function(tabId) {
  109. onClosedClient(tabId.toString());
  110. };
  111. chrome.webNavigation.onCreatedNavigationTarget.addListener(onCreatedNavigationTarget);
  112. chrome.webNavigation.onCommitted.addListener(onCommitted);
  113. chrome.tabs.onUpdated.addListener(onUpdated);
  114. chrome.tabs.onRemoved.addListener(onClosed);
  115. };
  116. /******************************************************************************/
  117. // tabId: null, // active tab
  118. vAPI.tabs.get = function(tabId, callback) {
  119. var onTabReady = function(tab) {
  120. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  121. if ( chrome.runtime.lastError ) {
  122. }
  123. if ( tab instanceof Object ) {
  124. tab.id = tab.id.toString();
  125. }
  126. callback(tab);
  127. };
  128. if ( tabId !== null ) {
  129. if ( typeof tabId === 'string' ) {
  130. tabId = parseInt(tabId, 10);
  131. }
  132. chrome.tabs.get(tabId, onTabReady);
  133. return;
  134. }
  135. var onTabReceived = function(tabs) {
  136. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  137. if ( chrome.runtime.lastError ) {
  138. }
  139. var tab = null;
  140. if ( Array.isArray(tabs) && tabs.length !== 0 ) {
  141. tab = tabs[0];
  142. tab.id = tab.id.toString();
  143. }
  144. callback(tab);
  145. };
  146. chrome.tabs.query({ active: true, currentWindow: true }, onTabReceived);
  147. };
  148. /******************************************************************************/
  149. vAPI.tabs.getAll = function(callback) {
  150. var onTabsReady = function(tabs) {
  151. if ( Array.isArray(tabs) ) {
  152. var i = tabs.length;
  153. while ( i-- ) {
  154. tabs[i].id = tabs[i].id.toString();
  155. }
  156. }
  157. callback(tabs);
  158. };
  159. chrome.tabs.query({ url: '<all_urls>' }, onTabsReady);
  160. };
  161. /******************************************************************************/
  162. // properties of the details object:
  163. // url: 'URL', // the address that will be opened
  164. // tabId: 1, // the tab is used if set, instead of creating a new one
  165. // index: -1, // undefined: end of the list, -1: following tab, or after index
  166. // active: false, // opens the tab in background - true and undefined: foreground
  167. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  168. vAPI.tabs.open = function(details) {
  169. var targetURL = details.url;
  170. if ( typeof targetURL !== 'string' || targetURL === '' ) {
  171. return null;
  172. }
  173. // extension pages
  174. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  175. targetURL = vAPI.getURL(targetURL);
  176. }
  177. // dealing with Chrome's asynchronous API
  178. var wrapper = function() {
  179. if ( details.active === undefined ) {
  180. details.active = true;
  181. }
  182. var subWrapper = function() {
  183. var _details = {
  184. url: targetURL,
  185. active: !!details.active
  186. };
  187. // Opening a tab from incognito window won't focus the window
  188. // in which the tab was opened
  189. var focusWindow = function(tab) {
  190. if ( tab.active ) {
  191. chrome.windows.update(tab.windowId, { focused: true });
  192. }
  193. };
  194. if ( !details.tabId ) {
  195. if ( details.index !== undefined ) {
  196. _details.index = details.index;
  197. }
  198. chrome.tabs.create(_details, focusWindow);
  199. return;
  200. }
  201. // update doesn't accept index, must use move
  202. chrome.tabs.update(parseInt(details.tabId, 10), _details, function(tab) {
  203. // if the tab doesn't exist
  204. if ( vAPI.lastError() ) {
  205. chrome.tabs.create(_details, focusWindow);
  206. } else if ( details.index !== undefined ) {
  207. chrome.tabs.move(tab.id, {index: details.index});
  208. }
  209. });
  210. };
  211. // Open in a standalone window
  212. if ( details.popup === true ) {
  213. chrome.windows.create({ url: details.url, type: 'popup' });
  214. return;
  215. }
  216. if ( details.index !== -1 ) {
  217. subWrapper();
  218. return;
  219. }
  220. vAPI.tabs.get(null, function(tab) {
  221. if ( tab ) {
  222. details.index = tab.index + 1;
  223. } else {
  224. delete details.index;
  225. }
  226. subWrapper();
  227. });
  228. };
  229. if ( !details.select ) {
  230. wrapper();
  231. return;
  232. }
  233. chrome.tabs.query({ url: targetURL }, function(tabs) {
  234. if ( chrome.runtime.lastError ) { /* noop */ }
  235. var tab = Array.isArray(tabs) && tabs[0];
  236. if ( tab ) {
  237. chrome.tabs.update(tab.id, { active: true }, function(tab) {
  238. chrome.windows.update(tab.windowId, { focused: true });
  239. });
  240. } else {
  241. wrapper();
  242. }
  243. });
  244. };
  245. /******************************************************************************/
  246. // Replace the URL of a tab. Noop if the tab does not exist.
  247. vAPI.tabs.replace = function(tabId, url) {
  248. var targetURL = url;
  249. // extension pages
  250. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  251. targetURL = vAPI.getURL(targetURL);
  252. }
  253. if ( typeof tabId !== 'number' ) {
  254. tabId = parseInt(tabId, 10);
  255. if ( isNaN(tabId) ) {
  256. return;
  257. }
  258. }
  259. chrome.tabs.update(tabId, { url: targetURL }, function() {
  260. // this prevent console error
  261. if ( chrome.runtime.lastError ) {
  262. return;
  263. }
  264. });
  265. };
  266. /******************************************************************************/
  267. vAPI.tabs.remove = function(tabId) {
  268. var onTabRemoved = function() {
  269. if ( vAPI.lastError() ) {
  270. }
  271. };
  272. chrome.tabs.remove(parseInt(tabId, 10), onTabRemoved);
  273. };
  274. /******************************************************************************/
  275. vAPI.tabs.reload = function(tabId, bypassCache) {
  276. if ( typeof tabId === 'string' ) {
  277. tabId = parseInt(tabId, 10);
  278. }
  279. if ( isNaN(tabId) ) {
  280. return;
  281. }
  282. chrome.tabs.reload(tabId, { bypassCache: bypassCache === true });
  283. };
  284. /******************************************************************************/
  285. vAPI.tabs.injectScript = function(tabId, details, callback) {
  286. var onScriptExecuted = function() {
  287. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  288. if ( chrome.runtime.lastError ) {
  289. }
  290. if ( typeof callback === 'function' ) {
  291. callback();
  292. }
  293. };
  294. if ( tabId ) {
  295. tabId = parseInt(tabId, 10);
  296. chrome.tabs.executeScript(tabId, details, onScriptExecuted);
  297. } else {
  298. chrome.tabs.executeScript(details, onScriptExecuted);
  299. }
  300. };
  301. /******************************************************************************/
  302. // Must read: https://code.google.com/p/chromium/issues/detail?id=410868#c8
  303. // https://github.com/chrisaljoudi/uBlock/issues/19
  304. // https://github.com/chrisaljoudi/uBlock/issues/207
  305. // Since we may be called asynchronously, the tab id may not exist
  306. // anymore, so this ensures it does still exist.
  307. vAPI.setIcon = function(tabId, iconId, badge) {
  308. tabId = parseInt(tabId, 10);
  309. if ( isNaN(tabId) || tabId <= 0 ) {
  310. return;
  311. }
  312. var onIconReady = function() {
  313. if ( vAPI.lastError() ) {
  314. return;
  315. }
  316. chrome.browserAction.setBadgeText({ tabId: tabId, text: badge });
  317. if ( badge !== '' ) {
  318. chrome.browserAction.setBadgeBackgroundColor({
  319. tabId: tabId,
  320. color: '#000'
  321. });
  322. }
  323. };
  324. var iconSelector = typeof iconId === 'number' ? iconId : 'off';
  325. var iconPaths = {
  326. '19': 'img/browsericons/icon19-' + iconSelector + '.png'/* ,
  327. '38': 'img/browsericons/icon38-' + iconSelector + '.png' */
  328. };
  329. chrome.browserAction.setIcon({ tabId: tabId, path: iconPaths }, onIconReady);
  330. };
  331. /******************************************************************************/
  332. /******************************************************************************/
  333. vAPI.messaging = {
  334. ports: {},
  335. listeners: {},
  336. defaultHandler: null,
  337. NOOPFUNC: noopFunc,
  338. UNHANDLED: 'vAPI.messaging.notHandled'
  339. };
  340. /******************************************************************************/
  341. vAPI.messaging.listen = function(listenerName, callback) {
  342. this.listeners[listenerName] = callback;
  343. };
  344. /******************************************************************************/
  345. vAPI.messaging.onPortMessage = function(request, port) {
  346. var callback = vAPI.messaging.NOOPFUNC;
  347. if ( request.requestId !== undefined ) {
  348. callback = CallbackWrapper.factory(port, request).callback;
  349. }
  350. // Specific handler
  351. var r = vAPI.messaging.UNHANDLED;
  352. var listener = vAPI.messaging.listeners[request.channelName];
  353. if ( typeof listener === 'function' ) {
  354. r = listener(request.msg, port.sender, callback);
  355. }
  356. if ( r !== vAPI.messaging.UNHANDLED ) {
  357. return;
  358. }
  359. // Default handler
  360. r = vAPI.messaging.defaultHandler(request.msg, port.sender, callback);
  361. if ( r !== vAPI.messaging.UNHANDLED ) {
  362. return;
  363. }
  364. console.error('µMatrix> messaging > unknown request: %o', request);
  365. // Unhandled:
  366. // Need to callback anyways in case caller expected an answer, or
  367. // else there is a memory leak on caller's side
  368. callback();
  369. };
  370. /******************************************************************************/
  371. vAPI.messaging.onPortDisconnect = function(port) {
  372. port.onDisconnect.removeListener(vAPI.messaging.onPortDisconnect);
  373. port.onMessage.removeListener(vAPI.messaging.onPortMessage);
  374. delete vAPI.messaging.ports[port.name];
  375. };
  376. /******************************************************************************/
  377. vAPI.messaging.onPortConnect = function(port) {
  378. port.onDisconnect.addListener(vAPI.messaging.onPortDisconnect);
  379. port.onMessage.addListener(vAPI.messaging.onPortMessage);
  380. vAPI.messaging.ports[port.name] = port;
  381. };
  382. /******************************************************************************/
  383. vAPI.messaging.setup = function(defaultHandler) {
  384. // Already setup?
  385. if ( this.defaultHandler !== null ) {
  386. return;
  387. }
  388. if ( typeof defaultHandler !== 'function' ) {
  389. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  390. }
  391. this.defaultHandler = defaultHandler;
  392. chrome.runtime.onConnect.addListener(this.onPortConnect);
  393. };
  394. /******************************************************************************/
  395. vAPI.messaging.broadcast = function(message) {
  396. var messageWrapper = {
  397. broadcast: true,
  398. msg: message
  399. };
  400. for ( var portName in this.ports ) {
  401. if ( this.ports.hasOwnProperty(portName) === false ) {
  402. continue;
  403. }
  404. this.ports[portName].postMessage(messageWrapper);
  405. }
  406. };
  407. /******************************************************************************/
  408. // This allows to avoid creating a closure for every single message which
  409. // expects an answer. Having a closure created each time a message is processed
  410. // has been always bothering me. Another benefit of the implementation here
  411. // is to reuse the callback proxy object, so less memory churning.
  412. //
  413. // https://developers.google.com/speed/articles/optimizing-javascript
  414. // "Creating a closure is significantly slower then creating an inner
  415. // function without a closure, and much slower than reusing a static
  416. // function"
  417. //
  418. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  419. // "the dreaded 'uniformly slow code' case where every function takes 1%
  420. // of CPU and you have to make one hundred separate performance optimizations
  421. // to improve performance at all"
  422. //
  423. // http://jsperf.com/closure-no-closure/2
  424. var CallbackWrapper = function(port, request) {
  425. // No need to bind every single time
  426. this.callback = this.proxy.bind(this);
  427. this.messaging = vAPI.messaging;
  428. this.init(port, request);
  429. };
  430. CallbackWrapper.junkyard = [];
  431. CallbackWrapper.factory = function(port, request) {
  432. var wrapper = CallbackWrapper.junkyard.pop();
  433. if ( wrapper ) {
  434. wrapper.init(port, request);
  435. return wrapper;
  436. }
  437. return new CallbackWrapper(port, request);
  438. };
  439. CallbackWrapper.prototype.init = function(port, request) {
  440. this.port = port;
  441. this.request = request;
  442. };
  443. CallbackWrapper.prototype.proxy = function(response) {
  444. // https://github.com/chrisaljoudi/uBlock/issues/383
  445. if ( this.messaging.ports.hasOwnProperty(this.port.name) ) {
  446. this.port.postMessage({
  447. requestId: this.request.requestId,
  448. channelName: this.request.channelName,
  449. msg: response !== undefined ? response : null
  450. });
  451. }
  452. // Mark for reuse
  453. this.port = this.request = null;
  454. CallbackWrapper.junkyard.push(this);
  455. };
  456. /******************************************************************************/
  457. /******************************************************************************/
  458. vAPI.net = {};
  459. /******************************************************************************/
  460. vAPI.net.registerListeners = function() {
  461. var µm = µMatrix,
  462. reNetworkURL = /^(?:https?|wss?):\/\//,
  463. httpRequestHeadersJunkyard = [];
  464. // Abstraction layer to deal with request headers
  465. // >>>>>>>>
  466. var httpRequestHeadersFactory = function(headers) {
  467. var entry = httpRequestHeadersJunkyard.pop();
  468. if ( entry ) {
  469. return entry.init(headers);
  470. }
  471. return new HTTPRequestHeaders(headers);
  472. };
  473. var HTTPRequestHeaders = function(headers) {
  474. this.init(headers);
  475. };
  476. HTTPRequestHeaders.prototype.init = function(headers) {
  477. this.modified = false;
  478. this.headers = headers;
  479. return this;
  480. };
  481. HTTPRequestHeaders.prototype.dispose = function() {
  482. var r = this.modified ? this.headers : null;
  483. this.headers = null;
  484. httpRequestHeadersJunkyard.push(this);
  485. return r;
  486. };
  487. HTTPRequestHeaders.prototype.getHeader = function(target) {
  488. var headers = this.headers;
  489. var header, name;
  490. var i = headers.length;
  491. while ( i-- ) {
  492. header = headers[i];
  493. name = header.name.toLowerCase();
  494. if ( name === target ) {
  495. return header.value;
  496. }
  497. }
  498. return '';
  499. };
  500. HTTPRequestHeaders.prototype.setHeader = function(target, value, create) {
  501. var headers = this.headers;
  502. var header, name;
  503. var i = headers.length;
  504. while ( i-- ) {
  505. header = headers[i];
  506. name = header.name.toLowerCase();
  507. if ( name === target ) {
  508. break;
  509. }
  510. }
  511. if ( i < 0 && !create ) { // Header not found, don't add it
  512. return false;
  513. }
  514. if ( i < 0 ) { // Header not found, add it
  515. headers.push({ name: target, value: value });
  516. } else if ( value === '' ) { // Header found, remove it
  517. headers.splice(i, 1);
  518. } else { // Header found, modify it
  519. header.value = value;
  520. }
  521. this.modified = true;
  522. return true;
  523. };
  524. // <<<<<<<<
  525. // End of: Abstraction layer to deal with request headers
  526. // Normalizing request types
  527. // >>>>>>>>
  528. var extToTypeMap = new Map([
  529. ['eot','font'],['otf','font'],['svg','font'],['ttf','font'],['woff','font'],['woff2','font'],
  530. ['mp3','media'],['mp4','media'],['webm','media'],
  531. ['gif','image'],['ico','image'],['jpeg','image'],['jpg','image'],['png','image'],['webp','image']
  532. ]);
  533. var normalizeRequestDetails = function(details) {
  534. details.tabId = details.tabId.toString();
  535. var type = details.type;
  536. if ( type === 'imageset' ) {
  537. details.type = 'image';
  538. return;
  539. }
  540. // The rest of the function code is to normalize request type
  541. if ( type !== 'other' ) {
  542. return;
  543. }
  544. if ( details.requestHeaders instanceof HTTPRequestHeaders ) {
  545. if ( details.requestHeaders.getHeader('ping-to') !== '' ) {
  546. details.type = 'ping';
  547. return;
  548. }
  549. }
  550. // Try to map known "extension" part of URL to request type.
  551. var path = µm.URI.pathFromURI(details.url),
  552. pos = path.indexOf('.', path.length - 6);
  553. if ( pos !== -1 && (type = extToTypeMap.get(path.slice(pos + 1))) ) {
  554. details.type = type;
  555. }
  556. };
  557. // <<<<<<<<
  558. // End of: Normalizing request types
  559. // Network event handlers
  560. // >>>>>>>>
  561. var onBeforeRequestClient = this.onBeforeRequest.callback;
  562. chrome.webRequest.onBeforeRequest.addListener(
  563. function(details) {
  564. if ( reNetworkURL.test(details.url) ) {
  565. normalizeRequestDetails(details);
  566. return onBeforeRequestClient(details);
  567. }
  568. },
  569. //function(details) {
  570. // quickProfiler.start('onBeforeRequest');
  571. // var r = onBeforeRequest(details);
  572. // quickProfiler.stop();
  573. // return r;
  574. //},
  575. {
  576. 'urls': this.onBeforeRequest.urls || [ '<all_urls>' ],
  577. 'types': this.onBeforeRequest.types || undefined
  578. },
  579. this.onBeforeRequest.extra
  580. );
  581. var onBeforeSendHeadersClient = this.onBeforeSendHeaders.callback;
  582. var onBeforeSendHeaders = function(details) {
  583. details.requestHeaders = httpRequestHeadersFactory(details.requestHeaders);
  584. normalizeRequestDetails(details);
  585. var result = onBeforeSendHeadersClient(details);
  586. if ( typeof result === 'object' ) {
  587. return result;
  588. }
  589. var modifiedHeaders = details.requestHeaders.dispose();
  590. if ( modifiedHeaders !== null ) {
  591. return { requestHeaders: modifiedHeaders };
  592. }
  593. };
  594. chrome.webRequest.onBeforeSendHeaders.addListener(
  595. onBeforeSendHeaders,
  596. {
  597. 'urls': this.onBeforeSendHeaders.urls || [ '<all_urls>' ],
  598. 'types': this.onBeforeSendHeaders.types || undefined
  599. },
  600. this.onBeforeSendHeaders.extra
  601. );
  602. var onHeadersReceivedClient = this.onHeadersReceived.callback;
  603. var onHeadersReceived = function(details) {
  604. normalizeRequestDetails(details);
  605. return onHeadersReceivedClient(details);
  606. };
  607. chrome.webRequest.onHeadersReceived.addListener(
  608. onHeadersReceived,
  609. {
  610. 'urls': this.onHeadersReceived.urls || [ '<all_urls>' ],
  611. 'types': this.onHeadersReceived.types || undefined
  612. },
  613. this.onHeadersReceived.extra
  614. );
  615. // <<<<<<<<
  616. // End of: Network event handlers
  617. };
  618. /******************************************************************************/
  619. /******************************************************************************/
  620. vAPI.contextMenu = {
  621. create: function(details, callback) {
  622. this.menuId = details.id;
  623. this.callback = callback;
  624. chrome.contextMenus.create(details);
  625. chrome.contextMenus.onClicked.addListener(this.callback);
  626. },
  627. remove: function() {
  628. chrome.contextMenus.onClicked.removeListener(this.callback);
  629. chrome.contextMenus.remove(this.menuId);
  630. }
  631. };
  632. /******************************************************************************/
  633. vAPI.lastError = function() {
  634. return chrome.runtime.lastError;
  635. };
  636. /******************************************************************************/
  637. /******************************************************************************/
  638. // This is called only once, when everything has been loaded in memory after
  639. // the extension was launched. It can be used to inject content scripts
  640. // in already opened web pages, to remove whatever nuisance could make it to
  641. // the web pages before uBlock was ready.
  642. vAPI.onLoadAllCompleted = function() {
  643. };
  644. /******************************************************************************/
  645. /******************************************************************************/
  646. vAPI.punycodeHostname = function(hostname) {
  647. return hostname;
  648. };
  649. vAPI.punycodeURL = function(url) {
  650. return url;
  651. };
  652. /******************************************************************************/
  653. /******************************************************************************/
  654. vAPI.browserData = {};
  655. /******************************************************************************/
  656. // https://developer.chrome.com/extensions/browsingData
  657. vAPI.browserData.clearCache = function(callback) {
  658. chrome.browsingData.removeCache({ since: 0 }, callback);
  659. };
  660. /******************************************************************************/
  661. // Not supported on Chromium
  662. vAPI.browserData.clearOrigin = function(domain, callback) {
  663. // unsupported on Chromium
  664. if ( typeof callback === 'function' ) {
  665. callback(undefined);
  666. }
  667. };
  668. /******************************************************************************/
  669. /******************************************************************************/
  670. // https://developer.chrome.com/extensions/cookies
  671. vAPI.cookies = {};
  672. /******************************************************************************/
  673. vAPI.cookies.start = function() {
  674. var reallyRemoved = {
  675. 'evicted': true,
  676. 'expired': true,
  677. 'explicit': true
  678. };
  679. var onChanged = function(changeInfo) {
  680. if ( changeInfo.removed ) {
  681. if ( reallyRemoved[changeInfo.cause] && typeof this.onRemoved === 'function' ) {
  682. this.onRemoved(changeInfo.cookie);
  683. }
  684. return;
  685. }
  686. if ( typeof this.onChanged === 'function' ) {
  687. this.onChanged(changeInfo.cookie);
  688. }
  689. };
  690. chrome.cookies.onChanged.addListener(onChanged.bind(this));
  691. };
  692. /******************************************************************************/
  693. vAPI.cookies.getAll = function(callback) {
  694. chrome.cookies.getAll({}, callback);
  695. };
  696. /******************************************************************************/
  697. vAPI.cookies.remove = function(details, callback) {
  698. chrome.cookies.remove(details, callback || noopFunc);
  699. };
  700. /******************************************************************************/
  701. /******************************************************************************/
  702. vAPI.cloud = (function() {
  703. // Not all platforms support `chrome.storage.sync`.
  704. if ( chrome.storage.sync instanceof Object === false ) {
  705. return;
  706. }
  707. var chunkCountPerFetch = 16; // Must be a power of 2
  708. // Mind chrome.storage.sync.MAX_ITEMS (512 at time of writing)
  709. var maxChunkCountPerItem = Math.floor(512 * 0.75) & ~(chunkCountPerFetch - 1);
  710. // Mind chrome.storage.sync.QUOTA_BYTES_PER_ITEM (8192 at time of writing)
  711. var maxChunkSize = chrome.storage.sync.QUOTA_BYTES_PER_ITEM || 8192;
  712. // Mind chrome.storage.sync.QUOTA_BYTES (128 kB at time of writing)
  713. // Firefox:
  714. // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/storage/sync
  715. // > You can store up to 100KB of data using this API/
  716. var maxStorageSize = chrome.storage.sync.QUOTA_BYTES || 102400;
  717. // Flavor-specific handling needs to be done here. Reason: to allow time
  718. // for vAPI.webextFlavor to be properly set.
  719. // https://github.com/gorhill/uBlock/issues/3006
  720. // For Firefox, we will use a lower ratio to allow for more overhead for
  721. // the infrastructure. Unfortunately this leads to less usable space for
  722. // actual data, but all of this is provided for free by browser vendors,
  723. // so we need to accept and deal with these limitations.
  724. var initialize = function() {
  725. var ratio = vAPI.webextFlavor.startsWith('Mozilla-Firefox-') ? 0.6 : 0.75;
  726. maxChunkSize = Math.floor(maxChunkSize * ratio);
  727. initialize = function(){};
  728. };
  729. var options = {
  730. defaultDeviceName: window.navigator.platform,
  731. deviceName: vAPI.localStorage.getItem('deviceName') || ''
  732. };
  733. // This is used to find out a rough count of how many chunks exists:
  734. // We "poll" at specific index in order to get a rough idea of how
  735. // large is the stored string.
  736. // This allows reading a single item with only 2 sync operations -- a
  737. // good thing given chrome.storage.sync.MAX_WRITE_OPERATIONS_PER_MINUTE
  738. // and chrome.storage.sync.MAX_WRITE_OPERATIONS_PER_HOUR.
  739. var getCoarseChunkCount = function(dataKey, callback) {
  740. var bin = {};
  741. for ( var i = 0; i < maxChunkCountPerItem; i += 16 ) {
  742. bin[dataKey + i.toString()] = '';
  743. }
  744. chrome.storage.sync.get(bin, function(bin) {
  745. if ( chrome.runtime.lastError ) {
  746. callback(0, chrome.runtime.lastError.message);
  747. return;
  748. }
  749. var chunkCount = 0;
  750. for ( var i = 0; i < maxChunkCountPerItem; i += 16 ) {
  751. if ( bin[dataKey + i.toString()] === '' ) {
  752. break;
  753. }
  754. chunkCount = i + 16;
  755. }
  756. callback(chunkCount);
  757. });
  758. };
  759. var deleteChunks = function(dataKey, start) {
  760. var keys = [];
  761. // No point in deleting more than:
  762. // - The max number of chunks per item
  763. // - The max number of chunks per storage limit
  764. var n = Math.min(
  765. maxChunkCountPerItem,
  766. Math.ceil(maxStorageSize / maxChunkSize)
  767. );
  768. for ( var i = start; i < n; i++ ) {
  769. keys.push(dataKey + i.toString());
  770. }
  771. chrome.storage.sync.remove(keys);
  772. };
  773. var start = function(/* dataKeys */) {
  774. };
  775. var push = function(dataKey, data, callback) {
  776. initialize();
  777. var bin = {
  778. 'source': options.deviceName || options.defaultDeviceName,
  779. 'tstamp': Date.now(),
  780. 'data': data,
  781. 'size': 0
  782. };
  783. bin.size = JSON.stringify(bin).length;
  784. var item = JSON.stringify(bin);
  785. // Chunkify taking into account QUOTA_BYTES_PER_ITEM:
  786. // https://developer.chrome.com/extensions/storage#property-sync
  787. // "The maximum size (in bytes) of each individual item in sync
  788. // "storage, as measured by the JSON stringification of its value
  789. // "plus its key length."
  790. bin = {};
  791. var chunkCount = Math.ceil(item.length / maxChunkSize);
  792. for ( var i = 0; i < chunkCount; i++ ) {
  793. bin[dataKey + i.toString()] = item.substr(i * maxChunkSize, maxChunkSize);
  794. }
  795. bin[dataKey + i.toString()] = ''; // Sentinel
  796. chrome.storage.sync.set(bin, function() {
  797. var errorStr;
  798. if ( chrome.runtime.lastError ) {
  799. errorStr = chrome.runtime.lastError.message;
  800. // https://github.com/gorhill/uBlock/issues/3006#issuecomment-332597677
  801. // - Delete all that was pushed in case of failure.
  802. chunkCount = 0;
  803. }
  804. callback(errorStr);
  805. // Remove potentially unused trailing chunks
  806. deleteChunks(dataKey, chunkCount);
  807. });
  808. };
  809. var pull = function(dataKey, callback) {
  810. initialize();
  811. var assembleChunks = function(bin) {
  812. if ( chrome.runtime.lastError ) {
  813. callback(null, chrome.runtime.lastError.message);
  814. return;
  815. }
  816. // Assemble chunks into a single string.
  817. var json = [], jsonSlice;
  818. var i = 0;
  819. for (;;) {
  820. jsonSlice = bin[dataKey + i.toString()];
  821. if ( jsonSlice === '' ) {
  822. break;
  823. }
  824. json.push(jsonSlice);
  825. i += 1;
  826. }
  827. var entry = null;
  828. try {
  829. entry = JSON.parse(json.join(''));
  830. } catch(ex) {
  831. }
  832. callback(entry);
  833. };
  834. var fetchChunks = function(coarseCount, errorStr) {
  835. if ( coarseCount === 0 || typeof errorStr === 'string' ) {
  836. callback(null, errorStr);
  837. return;
  838. }
  839. var bin = {};
  840. for ( var i = 0; i < coarseCount; i++ ) {
  841. bin[dataKey + i.toString()] = '';
  842. }
  843. chrome.storage.sync.get(bin, assembleChunks);
  844. };
  845. getCoarseChunkCount(dataKey, fetchChunks);
  846. };
  847. var getOptions = function(callback) {
  848. if ( typeof callback !== 'function' ) {
  849. return;
  850. }
  851. callback(options);
  852. };
  853. var setOptions = function(details, callback) {
  854. if ( typeof details !== 'object' || details === null ) {
  855. return;
  856. }
  857. if ( typeof details.deviceName === 'string' ) {
  858. vAPI.localStorage.setItem('deviceName', details.deviceName);
  859. options.deviceName = details.deviceName;
  860. }
  861. getOptions(callback);
  862. };
  863. return {
  864. start: start,
  865. push: push,
  866. pull: pull,
  867. getOptions: getOptions,
  868. setOptions: setOptions
  869. };
  870. })();
  871. /******************************************************************************/
  872. /******************************************************************************/
  873. })();
  874. /******************************************************************************/