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.

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