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.

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