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.

1062 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
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: new Map(),
  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() {
  346. var messaging = vAPI.messaging;
  347. // Use a wrapper to avoid closure and to allow reuse.
  348. var CallbackWrapper = function(port, request) {
  349. this.callback = this.proxy.bind(this); // bind once
  350. this.init(port, request);
  351. };
  352. CallbackWrapper.prototype = {
  353. init: function(port, request) {
  354. this.port = port;
  355. this.request = request;
  356. return this;
  357. },
  358. proxy: function(response) {
  359. // https://github.com/chrisaljoudi/uBlock/issues/383
  360. if ( messaging.ports.has(this.port.name) ) {
  361. this.port.postMessage({
  362. auxProcessId: this.request.auxProcessId,
  363. channelName: this.request.channelName,
  364. msg: response !== undefined ? response : null
  365. });
  366. }
  367. // Mark for reuse
  368. this.port = this.request = null;
  369. callbackWrapperJunkyard.push(this);
  370. }
  371. };
  372. var callbackWrapperJunkyard = [];
  373. var callbackWrapperFactory = function(port, request) {
  374. var wrapper = callbackWrapperJunkyard.pop();
  375. if ( wrapper ) {
  376. return wrapper.init(port, request);
  377. }
  378. return new CallbackWrapper(port, request);
  379. };
  380. // https://bugzilla.mozilla.org/show_bug.cgi?id=1392067
  381. // Workaround: manually remove ports matching removed tab.
  382. chrome.tabs.onRemoved.addListener(function(tabId) {
  383. for ( var port of messaging.ports.values() ) {
  384. var tab = port.sender && port.sender.tab;
  385. if ( !tab ) { continue; }
  386. if ( tab.id === tabId ) {
  387. vAPI.messaging.onPortDisconnect(port);
  388. }
  389. }
  390. });
  391. return function(request, port) {
  392. // prepare response
  393. var callback = this.NOOPFUNC;
  394. if ( request.auxProcessId !== undefined ) {
  395. callback = callbackWrapperFactory(port, request).callback;
  396. }
  397. // Auxiliary process to main process: specific handler
  398. var r = this.UNHANDLED,
  399. listener = this.listeners[request.channelName];
  400. if ( typeof listener === 'function' ) {
  401. r = listener(request.msg, port.sender, callback);
  402. }
  403. if ( r !== this.UNHANDLED ) { return; }
  404. // Auxiliary process to main process: default handler
  405. r = this.defaultHandler(request.msg, port.sender, callback);
  406. if ( r !== this.UNHANDLED ) { return; }
  407. // Auxiliary process to main process: no handler
  408. console.error(
  409. 'vAPI.messaging.onPortMessage > unhandled request: %o',
  410. request
  411. );
  412. // Need to callback anyways in case caller expected an answer, or
  413. // else there is a memory leak on caller's side
  414. callback();
  415. }.bind(vAPI.messaging);
  416. })();
  417. /******************************************************************************/
  418. vAPI.messaging.onPortDisconnect = function(port) {
  419. port.onDisconnect.removeListener(this.onPortDisconnect);
  420. port.onMessage.removeListener(this.onPortMessage);
  421. this.ports.delete(port.name);
  422. }.bind(vAPI.messaging);
  423. /******************************************************************************/
  424. vAPI.messaging.onPortConnect = function(port) {
  425. port.onDisconnect.addListener(this.onPortDisconnect);
  426. port.onMessage.addListener(this.onPortMessage);
  427. this.ports.set(port.name, port);
  428. }.bind(vAPI.messaging);
  429. /******************************************************************************/
  430. vAPI.messaging.setup = function(defaultHandler) {
  431. if ( this.defaultHandler !== null ) { return; }
  432. if ( typeof defaultHandler !== 'function' ) {
  433. defaultHandler = function(){
  434. return vAPI.messaging.UNHANDLED;
  435. };
  436. }
  437. this.defaultHandler = defaultHandler;
  438. chrome.runtime.onConnect.addListener(this.onPortConnect);
  439. };
  440. /******************************************************************************/
  441. vAPI.messaging.broadcast = function(message) {
  442. var messageWrapper = {
  443. broadcast: true,
  444. msg: message
  445. };
  446. for ( var port of this.ports.values() ) {
  447. port.postMessage(messageWrapper);
  448. }
  449. };
  450. /******************************************************************************/
  451. /******************************************************************************/
  452. vAPI.net = {};
  453. /******************************************************************************/
  454. vAPI.net.registerListeners = function() {
  455. var µm = µMatrix,
  456. reNetworkURL = /^(?:https?|wss?):\/\//,
  457. httpRequestHeadersJunkyard = [];
  458. // Abstraction layer to deal with request headers
  459. // >>>>>>>>
  460. var httpRequestHeadersFactory = function(headers) {
  461. var entry = httpRequestHeadersJunkyard.pop();
  462. if ( entry ) {
  463. return entry.init(headers);
  464. }
  465. return new HTTPRequestHeaders(headers);
  466. };
  467. var HTTPRequestHeaders = function(headers) {
  468. this.init(headers);
  469. };
  470. HTTPRequestHeaders.prototype.init = function(headers) {
  471. this.modified = false;
  472. this.headers = headers;
  473. return this;
  474. };
  475. HTTPRequestHeaders.prototype.dispose = function() {
  476. var r = this.modified ? this.headers : null;
  477. this.headers = null;
  478. httpRequestHeadersJunkyard.push(this);
  479. return r;
  480. };
  481. HTTPRequestHeaders.prototype.getHeader = function(target) {
  482. var headers = this.headers;
  483. var header, name;
  484. var i = headers.length;
  485. while ( i-- ) {
  486. header = headers[i];
  487. name = header.name.toLowerCase();
  488. if ( name === target ) {
  489. return header.value;
  490. }
  491. }
  492. return '';
  493. };
  494. HTTPRequestHeaders.prototype.setHeader = function(target, value, create) {
  495. var headers = this.headers;
  496. var header, name;
  497. var i = headers.length;
  498. while ( i-- ) {
  499. header = headers[i];
  500. name = header.name.toLowerCase();
  501. if ( name === target ) {
  502. break;
  503. }
  504. }
  505. if ( i < 0 && !create ) { // Header not found, don't add it
  506. return false;
  507. }
  508. if ( i < 0 ) { // Header not found, add it
  509. headers.push({ name: target, value: value });
  510. } else if ( value === '' ) { // Header found, remove it
  511. headers.splice(i, 1);
  512. } else { // Header found, modify it
  513. header.value = value;
  514. }
  515. this.modified = true;
  516. return true;
  517. };
  518. // <<<<<<<<
  519. // End of: Abstraction layer to deal with request headers
  520. // Normalizing request types
  521. // >>>>>>>>
  522. var extToTypeMap = new Map([
  523. ['eot','font'],['otf','font'],['svg','font'],['ttf','font'],['woff','font'],['woff2','font'],
  524. ['mp3','media'],['mp4','media'],['webm','media'],
  525. ['gif','image'],['ico','image'],['jpeg','image'],['jpg','image'],['png','image'],['webp','image']
  526. ]);
  527. var normalizeRequestDetails = function(details) {
  528. details.tabId = details.tabId.toString();
  529. var type = details.type;
  530. if ( type === 'imageset' ) {
  531. details.type = 'image';
  532. return;
  533. }
  534. // The rest of the function code is to normalize request type
  535. if ( type !== 'other' ) {
  536. return;
  537. }
  538. if ( details.requestHeaders instanceof HTTPRequestHeaders ) {
  539. if ( details.requestHeaders.getHeader('ping-to') !== '' ) {
  540. details.type = 'ping';
  541. return;
  542. }
  543. }
  544. // Try to map known "extension" part of URL to request type.
  545. var path = µm.URI.pathFromURI(details.url),
  546. pos = path.indexOf('.', path.length - 6);
  547. if ( pos !== -1 && (type = extToTypeMap.get(path.slice(pos + 1))) ) {
  548. details.type = type;
  549. }
  550. };
  551. // <<<<<<<<
  552. // End of: Normalizing request types
  553. // Network event handlers
  554. // >>>>>>>>
  555. var onBeforeRequestClient = this.onBeforeRequest.callback;
  556. chrome.webRequest.onBeforeRequest.addListener(
  557. function(details) {
  558. if ( reNetworkURL.test(details.url) ) {
  559. normalizeRequestDetails(details);
  560. return onBeforeRequestClient(details);
  561. }
  562. },
  563. //function(details) {
  564. // quickProfiler.start('onBeforeRequest');
  565. // var r = onBeforeRequest(details);
  566. // quickProfiler.stop();
  567. // return r;
  568. //},
  569. {
  570. 'urls': this.onBeforeRequest.urls || [ '<all_urls>' ],
  571. 'types': this.onBeforeRequest.types || undefined
  572. },
  573. this.onBeforeRequest.extra
  574. );
  575. var onBeforeSendHeadersClient = this.onBeforeSendHeaders.callback;
  576. var onBeforeSendHeaders = function(details) {
  577. details.requestHeaders = httpRequestHeadersFactory(details.requestHeaders);
  578. normalizeRequestDetails(details);
  579. var result = onBeforeSendHeadersClient(details);
  580. if ( typeof result === 'object' ) {
  581. return result;
  582. }
  583. var modifiedHeaders = details.requestHeaders.dispose();
  584. if ( modifiedHeaders !== null ) {
  585. return { requestHeaders: modifiedHeaders };
  586. }
  587. };
  588. chrome.webRequest.onBeforeSendHeaders.addListener(
  589. onBeforeSendHeaders,
  590. {
  591. 'urls': this.onBeforeSendHeaders.urls || [ '<all_urls>' ],
  592. 'types': this.onBeforeSendHeaders.types || undefined
  593. },
  594. this.onBeforeSendHeaders.extra
  595. );
  596. var onHeadersReceivedClient = this.onHeadersReceived.callback;
  597. var onHeadersReceived = function(details) {
  598. normalizeRequestDetails(details);
  599. return onHeadersReceivedClient(details);
  600. };
  601. chrome.webRequest.onHeadersReceived.addListener(
  602. onHeadersReceived,
  603. {
  604. 'urls': this.onHeadersReceived.urls || [ '<all_urls>' ],
  605. 'types': this.onHeadersReceived.types || undefined
  606. },
  607. this.onHeadersReceived.extra
  608. );
  609. // <<<<<<<<
  610. // End of: Network event handlers
  611. };
  612. /******************************************************************************/
  613. /******************************************************************************/
  614. vAPI.contextMenu = {
  615. create: function(details, callback) {
  616. this.menuId = details.id;
  617. this.callback = callback;
  618. chrome.contextMenus.create(details);
  619. chrome.contextMenus.onClicked.addListener(this.callback);
  620. },
  621. remove: function() {
  622. chrome.contextMenus.onClicked.removeListener(this.callback);
  623. chrome.contextMenus.remove(this.menuId);
  624. }
  625. };
  626. /******************************************************************************/
  627. vAPI.lastError = function() {
  628. return chrome.runtime.lastError;
  629. };
  630. /******************************************************************************/
  631. /******************************************************************************/
  632. // This is called only once, when everything has been loaded in memory after
  633. // the extension was launched. It can be used to inject content scripts
  634. // in already opened web pages, to remove whatever nuisance could make it to
  635. // the web pages before uBlock was ready.
  636. vAPI.onLoadAllCompleted = function() {
  637. };
  638. /******************************************************************************/
  639. /******************************************************************************/
  640. vAPI.punycodeHostname = function(hostname) {
  641. return hostname;
  642. };
  643. vAPI.punycodeURL = function(url) {
  644. return url;
  645. };
  646. /******************************************************************************/
  647. /******************************************************************************/
  648. vAPI.browserData = {};
  649. /******************************************************************************/
  650. // https://developer.chrome.com/extensions/browsingData
  651. vAPI.browserData.clearCache = function(callback) {
  652. chrome.browsingData.removeCache({ since: 0 }, callback);
  653. };
  654. /******************************************************************************/
  655. // Not supported on Chromium
  656. vAPI.browserData.clearOrigin = function(domain, callback) {
  657. // unsupported on Chromium
  658. if ( typeof callback === 'function' ) {
  659. callback(undefined);
  660. }
  661. };
  662. /******************************************************************************/
  663. /******************************************************************************/
  664. // https://developer.chrome.com/extensions/cookies
  665. vAPI.cookies = {};
  666. /******************************************************************************/
  667. vAPI.cookies.start = function() {
  668. var reallyRemoved = {
  669. 'evicted': true,
  670. 'expired': true,
  671. 'explicit': true
  672. };
  673. var onChanged = function(changeInfo) {
  674. if ( changeInfo.removed ) {
  675. if ( reallyRemoved[changeInfo.cause] && typeof this.onRemoved === 'function' ) {
  676. this.onRemoved(changeInfo.cookie);
  677. }
  678. return;
  679. }
  680. if ( typeof this.onChanged === 'function' ) {
  681. this.onChanged(changeInfo.cookie);
  682. }
  683. };
  684. chrome.cookies.onChanged.addListener(onChanged.bind(this));
  685. };
  686. /******************************************************************************/
  687. vAPI.cookies.getAll = function(callback) {
  688. chrome.cookies.getAll({}, callback);
  689. };
  690. /******************************************************************************/
  691. vAPI.cookies.remove = function(details, callback) {
  692. chrome.cookies.remove(details, callback || noopFunc);
  693. };
  694. /******************************************************************************/
  695. /******************************************************************************/
  696. vAPI.cloud = (function() {
  697. // Not all platforms support `chrome.storage.sync`.
  698. if ( chrome.storage.sync instanceof Object === false ) {
  699. return;
  700. }
  701. var chunkCountPerFetch = 16; // Must be a power of 2
  702. // Mind chrome.storage.sync.MAX_ITEMS (512 at time of writing)
  703. var maxChunkCountPerItem = Math.floor(512 * 0.75) & ~(chunkCountPerFetch - 1);
  704. // Mind chrome.storage.sync.QUOTA_BYTES_PER_ITEM (8192 at time of writing)
  705. var maxChunkSize = chrome.storage.sync.QUOTA_BYTES_PER_ITEM || 8192;
  706. // Mind chrome.storage.sync.QUOTA_BYTES (128 kB at time of writing)
  707. // Firefox:
  708. // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/storage/sync
  709. // > You can store up to 100KB of data using this API/
  710. var maxStorageSize = chrome.storage.sync.QUOTA_BYTES || 102400;
  711. // Flavor-specific handling needs to be done here. Reason: to allow time
  712. // for vAPI.webextFlavor to be properly set.
  713. // https://github.com/gorhill/uBlock/issues/3006
  714. // For Firefox, we will use a lower ratio to allow for more overhead for
  715. // the infrastructure. Unfortunately this leads to less usable space for
  716. // actual data, but all of this is provided for free by browser vendors,
  717. // so we need to accept and deal with these limitations.
  718. var initialize = function() {
  719. var ratio = vAPI.webextFlavor.startsWith('Mozilla-Firefox-') ? 0.6 : 0.75;
  720. maxChunkSize = Math.floor(maxChunkSize * ratio);
  721. initialize = function(){};
  722. };
  723. var options = {
  724. defaultDeviceName: window.navigator.platform,
  725. deviceName: vAPI.localStorage.getItem('deviceName') || ''
  726. };
  727. // This is used to find out a rough count of how many chunks exists:
  728. // We "poll" at specific index in order to get a rough idea of how
  729. // large is the stored string.
  730. // This allows reading a single item with only 2 sync operations -- a
  731. // good thing given chrome.storage.sync.MAX_WRITE_OPERATIONS_PER_MINUTE
  732. // and chrome.storage.sync.MAX_WRITE_OPERATIONS_PER_HOUR.
  733. var getCoarseChunkCount = function(dataKey, callback) {
  734. var bin = {};
  735. for ( var i = 0; i < maxChunkCountPerItem; i += 16 ) {
  736. bin[dataKey + i.toString()] = '';
  737. }
  738. chrome.storage.sync.get(bin, function(bin) {
  739. if ( chrome.runtime.lastError ) {
  740. callback(0, chrome.runtime.lastError.message);
  741. return;
  742. }
  743. var chunkCount = 0;
  744. for ( var i = 0; i < maxChunkCountPerItem; i += 16 ) {
  745. if ( bin[dataKey + i.toString()] === '' ) {
  746. break;
  747. }
  748. chunkCount = i + 16;
  749. }
  750. callback(chunkCount);
  751. });
  752. };
  753. var deleteChunks = function(dataKey, start) {
  754. var keys = [];
  755. // No point in deleting more than:
  756. // - The max number of chunks per item
  757. // - The max number of chunks per storage limit
  758. var n = Math.min(
  759. maxChunkCountPerItem,
  760. Math.ceil(maxStorageSize / maxChunkSize)
  761. );
  762. for ( var i = start; i < n; i++ ) {
  763. keys.push(dataKey + i.toString());
  764. }
  765. chrome.storage.sync.remove(keys);
  766. };
  767. var start = function(/* dataKeys */) {
  768. };
  769. var push = function(dataKey, data, callback) {
  770. initialize();
  771. var bin = {
  772. 'source': options.deviceName || options.defaultDeviceName,
  773. 'tstamp': Date.now(),
  774. 'data': data,
  775. 'size': 0
  776. };
  777. bin.size = JSON.stringify(bin).length;
  778. var item = JSON.stringify(bin);
  779. // Chunkify taking into account QUOTA_BYTES_PER_ITEM:
  780. // https://developer.chrome.com/extensions/storage#property-sync
  781. // "The maximum size (in bytes) of each individual item in sync
  782. // "storage, as measured by the JSON stringification of its value
  783. // "plus its key length."
  784. bin = {};
  785. var chunkCount = Math.ceil(item.length / maxChunkSize);
  786. for ( var i = 0; i < chunkCount; i++ ) {
  787. bin[dataKey + i.toString()] = item.substr(i * maxChunkSize, maxChunkSize);
  788. }
  789. bin[dataKey + i.toString()] = ''; // Sentinel
  790. chrome.storage.sync.set(bin, function() {
  791. var errorStr;
  792. if ( chrome.runtime.lastError ) {
  793. errorStr = chrome.runtime.lastError.message;
  794. // https://github.com/gorhill/uBlock/issues/3006#issuecomment-332597677
  795. // - Delete all that was pushed in case of failure.
  796. chunkCount = 0;
  797. }
  798. callback(errorStr);
  799. // Remove potentially unused trailing chunks
  800. deleteChunks(dataKey, chunkCount);
  801. });
  802. };
  803. var pull = function(dataKey, callback) {
  804. initialize();
  805. var assembleChunks = function(bin) {
  806. if ( chrome.runtime.lastError ) {
  807. callback(null, chrome.runtime.lastError.message);
  808. return;
  809. }
  810. // Assemble chunks into a single string.
  811. var json = [], jsonSlice;
  812. var i = 0;
  813. for (;;) {
  814. jsonSlice = bin[dataKey + i.toString()];
  815. if ( jsonSlice === '' ) {
  816. break;
  817. }
  818. json.push(jsonSlice);
  819. i += 1;
  820. }
  821. var entry = null;
  822. try {
  823. entry = JSON.parse(json.join(''));
  824. } catch(ex) {
  825. }
  826. callback(entry);
  827. };
  828. var fetchChunks = function(coarseCount, errorStr) {
  829. if ( coarseCount === 0 || typeof errorStr === 'string' ) {
  830. callback(null, errorStr);
  831. return;
  832. }
  833. var bin = {};
  834. for ( var i = 0; i < coarseCount; i++ ) {
  835. bin[dataKey + i.toString()] = '';
  836. }
  837. chrome.storage.sync.get(bin, assembleChunks);
  838. };
  839. getCoarseChunkCount(dataKey, fetchChunks);
  840. };
  841. var getOptions = function(callback) {
  842. if ( typeof callback !== 'function' ) {
  843. return;
  844. }
  845. callback(options);
  846. };
  847. var setOptions = function(details, callback) {
  848. if ( typeof details !== 'object' || details === null ) {
  849. return;
  850. }
  851. if ( typeof details.deviceName === 'string' ) {
  852. vAPI.localStorage.setItem('deviceName', details.deviceName);
  853. options.deviceName = details.deviceName;
  854. }
  855. getOptions(callback);
  856. };
  857. return {
  858. start: start,
  859. push: push,
  860. pull: pull,
  861. getOptions: getOptions,
  862. setOptions: setOptions
  863. };
  864. })();
  865. /******************************************************************************/
  866. /******************************************************************************/
  867. })();
  868. /******************************************************************************/