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.

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