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.

897 lines
28 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
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. vAPI.app = {
  29. name: manifest.name,
  30. version: manifest.version
  31. };
  32. /******************************************************************************/
  33. vAPI.app.start = function() {
  34. // rhill 2013-12-07:
  35. // Relinquish control over javascript execution to the user.
  36. // https://github.com/gorhill/httpswitchboard/issues/74
  37. //chrome.contentSettings.javascript.clear({});
  38. };
  39. /******************************************************************************/
  40. vAPI.app.stop = function() {
  41. chrome.contentSettings.javascript.clear({});
  42. // rhill 2013-12-07:
  43. // Tell Chromium to allow all javascript: µMatrix will control whether
  44. // javascript execute through `Content-Policy-Directive` and webRequest.
  45. // https://github.com/gorhill/httpswitchboard/issues/74
  46. //chrome.contentSettings.javascript.set({
  47. // primaryPattern: 'https://*/*',
  48. // setting: 'allow'
  49. //});
  50. //chrome.contentSettings.javascript.set({
  51. // primaryPattern: 'http://*/*',
  52. // setting: 'allow'
  53. //});
  54. };
  55. /******************************************************************************/
  56. vAPI.app.restart = function() {
  57. chrome.runtime.reload();
  58. };
  59. /******************************************************************************/
  60. // chrome.storage.local.get(null, function(bin){ console.debug('%o', bin); });
  61. vAPI.storage = 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 onPopupClient = this.onPopup || noopFunc;
  73. var onUpdatedClient = this.onUpdated || noopFunc;
  74. var onClosedClient = this.onClosed || noopFunc;
  75. // https://developer.chrome.com/extensions/webNavigation
  76. // [onCreatedNavigationTarget ->]
  77. // onBeforeNavigate ->
  78. // onCommitted ->
  79. // onDOMContentLoaded ->
  80. // onCompleted
  81. var popupCandidates = Object.create(null);
  82. var PopupCandidate = function(details) {
  83. this.targetTabId = details.tabId;
  84. this.openerTabId = details.sourceTabId;
  85. this.targetURL = details.url;
  86. this.selfDestructionTimer = null;
  87. };
  88. PopupCandidate.prototype.selfDestruct = function() {
  89. if ( this.selfDestructionTimer !== null ) {
  90. clearTimeout(this.selfDestructionTimer);
  91. }
  92. delete popupCandidates[this.targetTabId];
  93. };
  94. PopupCandidate.prototype.launchSelfDestruction = function() {
  95. if ( this.selfDestructionTimer !== null ) {
  96. clearTimeout(this.selfDestructionTimer);
  97. }
  98. this.selfDestructionTimer = setTimeout(this.selfDestruct.bind(this), 10000);
  99. };
  100. var popupCandidateCreate = function(details) {
  101. var popup = popupCandidates[details.tabId];
  102. // This really should not happen...
  103. if ( popup !== undefined ) {
  104. return;
  105. }
  106. popup = popupCandidates[details.tabId] = new PopupCandidate(details);
  107. return popup;
  108. };
  109. var popupCandidateTest = function(details) {
  110. var popup = popupCandidates[details.tabId];
  111. if ( popup === undefined ) {
  112. return;
  113. }
  114. popup.targetURL = details.url;
  115. if ( onPopupClient(popup) !== true ) {
  116. return;
  117. }
  118. popup.selfDestruct();
  119. return true;
  120. };
  121. var popupCandidateDestroy = function(details) {
  122. var popup = popupCandidates[details.tabId];
  123. if ( popup instanceof PopupCandidate ) {
  124. popup.launchSelfDestruction();
  125. }
  126. };
  127. // The chrome.webRequest.onBeforeRequest() won't be called for everything
  128. // else than `http`/`https`. Thus, in such case, we will bind the tab as
  129. // early as possible in order to increase the likelihood of a context
  130. // properly setup if network requests are fired from within the tab.
  131. // Example: Chromium + case #6 at
  132. // http://raymondhill.net/ublock/popup.html
  133. var reGoodForWebRequestAPI = /^https?:\/\//;
  134. var onCreatedNavigationTarget = function(details) {
  135. details.tabId = details.tabId.toString();
  136. //console.debug('onCreatedNavigationTarget: popup candidate tab id %d = "%s"', details.tabId, details.url);
  137. if ( reGoodForWebRequestAPI.test(details.url) === false ) {
  138. details.frameId = 0;
  139. onNavigationClient(details);
  140. }
  141. popupCandidateCreate(details);
  142. popupCandidateTest(details);
  143. };
  144. var onBeforeNavigate = function(details) {
  145. if ( details.frameId !== 0 ) {
  146. return;
  147. }
  148. //console.debug('onBeforeNavigate: popup candidate tab id %d = "%s"', details.tabId, details.url);
  149. details.tabId = details.tabId.toString();
  150. popupCandidateTest(details);
  151. };
  152. var onUpdated = function(tabId, changeInfo, tab) {
  153. tabId = tabId.toString();
  154. if ( changeInfo.url && popupCandidateTest({ tabId: tabId, url: changeInfo.url }) ) {
  155. return;
  156. }
  157. onUpdatedClient(tabId, changeInfo, tab);
  158. };
  159. var onCommitted = function(details) {
  160. if ( details.frameId !== 0 ) {
  161. return;
  162. }
  163. details.tabId = details.tabId.toString();
  164. onNavigationClient(details);
  165. //console.debug('onCommitted: popup candidate tab id %d = "%s"', details.tabId, details.url);
  166. if ( popupCandidateTest(details) === true ) {
  167. return;
  168. }
  169. popupCandidateDestroy(details);
  170. };
  171. var onClosed = function(tabId) {
  172. onClosedClient(tabId.toString());
  173. };
  174. chrome.webNavigation.onCreatedNavigationTarget.addListener(onCreatedNavigationTarget);
  175. chrome.webNavigation.onBeforeNavigate.addListener(onBeforeNavigate);
  176. chrome.webNavigation.onCommitted.addListener(onCommitted);
  177. chrome.tabs.onUpdated.addListener(onUpdated);
  178. chrome.tabs.onRemoved.addListener(onClosed);
  179. };
  180. /******************************************************************************/
  181. // tabId: null, // active tab
  182. vAPI.tabs.get = function(tabId, callback) {
  183. var onTabReady = function(tab) {
  184. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  185. if ( chrome.runtime.lastError ) {
  186. }
  187. if ( tab instanceof Object ) {
  188. tab.id = tab.id.toString();
  189. }
  190. callback(tab);
  191. };
  192. if ( tabId !== null ) {
  193. if ( typeof tabId === 'string' ) {
  194. tabId = parseInt(tabId, 10);
  195. }
  196. chrome.tabs.get(tabId, onTabReady);
  197. return;
  198. }
  199. var onTabReceived = function(tabs) {
  200. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  201. if ( chrome.runtime.lastError ) {
  202. }
  203. var tab = null;
  204. if ( Array.isArray(tabs) && tabs.length !== 0 ) {
  205. tab = tabs[0];
  206. tab.id = tab.id.toString();
  207. }
  208. callback(tab);
  209. };
  210. chrome.tabs.query({ active: true, currentWindow: true }, onTabReceived);
  211. };
  212. /******************************************************************************/
  213. vAPI.tabs.getAll = function(callback) {
  214. var onTabsReady = function(tabs) {
  215. if ( Array.isArray(tabs) ) {
  216. var i = tabs.length;
  217. while ( i-- ) {
  218. tabs[i].id = tabs[i].id.toString();
  219. }
  220. }
  221. callback(tabs);
  222. };
  223. chrome.tabs.query({ url: '<all_urls>' }, onTabsReady);
  224. };
  225. /******************************************************************************/
  226. // properties of the details object:
  227. // url: 'URL', // the address that will be opened
  228. // tabId: 1, // the tab is used if set, instead of creating a new one
  229. // index: -1, // undefined: end of the list, -1: following tab, or after index
  230. // active: false, // opens the tab in background - true and undefined: foreground
  231. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  232. vAPI.tabs.open = function(details) {
  233. var targetURL = details.url;
  234. if ( typeof targetURL !== 'string' || targetURL === '' ) {
  235. return null;
  236. }
  237. // extension pages
  238. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  239. targetURL = vAPI.getURL(targetURL);
  240. }
  241. // dealing with Chrome's asynchronous API
  242. var wrapper = function() {
  243. if ( details.active === undefined ) {
  244. details.active = true;
  245. }
  246. var subWrapper = function() {
  247. var _details = {
  248. url: targetURL,
  249. active: !!details.active
  250. };
  251. // Opening a tab from incognito window won't focus the window
  252. // in which the tab was opened
  253. var focusWindow = function(tab) {
  254. if ( tab.active ) {
  255. chrome.windows.update(tab.windowId, { focused: true });
  256. }
  257. };
  258. if ( !details.tabId ) {
  259. if ( details.index !== undefined ) {
  260. _details.index = details.index;
  261. }
  262. chrome.tabs.create(_details, focusWindow);
  263. return;
  264. }
  265. // update doesn't accept index, must use move
  266. chrome.tabs.update(parseInt(details.tabId, 10), _details, function(tab) {
  267. // if the tab doesn't exist
  268. if ( vAPI.lastError() ) {
  269. chrome.tabs.create(_details, focusWindow);
  270. } else if ( details.index !== undefined ) {
  271. chrome.tabs.move(tab.id, {index: details.index});
  272. }
  273. });
  274. };
  275. if ( details.index !== -1 ) {
  276. subWrapper();
  277. return;
  278. }
  279. vAPI.tabs.get(null, function(tab) {
  280. if ( tab ) {
  281. details.index = tab.index + 1;
  282. } else {
  283. delete details.index;
  284. }
  285. subWrapper();
  286. });
  287. };
  288. if ( !details.select ) {
  289. wrapper();
  290. return;
  291. }
  292. chrome.tabs.query({ url: targetURL }, function(tabs) {
  293. var tab = tabs[0];
  294. if ( tab ) {
  295. chrome.tabs.update(tab.id, { active: true }, function(tab) {
  296. chrome.windows.update(tab.windowId, { focused: true });
  297. });
  298. } else {
  299. wrapper();
  300. }
  301. });
  302. };
  303. /******************************************************************************/
  304. // Replace the URL of a tab. Noop if the tab does not exist.
  305. vAPI.tabs.replace = function(tabId, url) {
  306. var targetURL = url;
  307. // extension pages
  308. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  309. targetURL = vAPI.getURL(targetURL);
  310. }
  311. if ( typeof tabId !== 'number' ) {
  312. tabId = parseInt(tabId, 10);
  313. if ( isNaN(tabId) ) {
  314. return;
  315. }
  316. }
  317. chrome.tabs.update(tabId, { url: targetURL }, function() {
  318. // this prevent console error
  319. if ( chrome.runtime.lastError ) {
  320. return;
  321. }
  322. });
  323. };
  324. /******************************************************************************/
  325. vAPI.tabs.remove = function(tabId) {
  326. var onTabRemoved = function() {
  327. if ( vAPI.lastError() ) {
  328. }
  329. };
  330. chrome.tabs.remove(parseInt(tabId, 10), onTabRemoved);
  331. };
  332. /******************************************************************************/
  333. vAPI.tabs.reload = function(tabId /*, flags*/) {
  334. if ( typeof tabId === 'string' ) {
  335. tabId = parseInt(tabId, 10);
  336. }
  337. if ( isNaN(tabId) ) {
  338. return;
  339. }
  340. chrome.tabs.reload(tabId);
  341. };
  342. /******************************************************************************/
  343. vAPI.tabs.injectScript = function(tabId, details, callback) {
  344. var onScriptExecuted = function() {
  345. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  346. if ( chrome.runtime.lastError ) {
  347. }
  348. if ( typeof callback === 'function' ) {
  349. callback();
  350. }
  351. };
  352. if ( tabId ) {
  353. tabId = parseInt(tabId, 10);
  354. chrome.tabs.executeScript(tabId, details, onScriptExecuted);
  355. } else {
  356. chrome.tabs.executeScript(details, onScriptExecuted);
  357. }
  358. };
  359. /******************************************************************************/
  360. // Must read: https://code.google.com/p/chromium/issues/detail?id=410868#c8
  361. // https://github.com/chrisaljoudi/uBlock/issues/19
  362. // https://github.com/chrisaljoudi/uBlock/issues/207
  363. // Since we may be called asynchronously, the tab id may not exist
  364. // anymore, so this ensures it does still exist.
  365. vAPI.setIcon = function(tabId, iconId, badge) {
  366. tabId = parseInt(tabId, 10);
  367. if ( isNaN(tabId) || tabId <= 0 ) {
  368. return;
  369. }
  370. var onIconReady = function() {
  371. if ( vAPI.lastError() ) {
  372. return;
  373. }
  374. chrome.browserAction.setBadgeText({ tabId: tabId, text: badge });
  375. if ( badge !== '' ) {
  376. chrome.browserAction.setBadgeBackgroundColor({
  377. tabId: tabId,
  378. color: '#000'
  379. });
  380. }
  381. };
  382. var iconSelector = typeof iconId === 'number' ? iconId : 'off';
  383. var iconPaths = {
  384. '19': 'img/browsericons/icon19-' + iconSelector + '.png'/* ,
  385. '38': 'img/browsericons/icon38-' + iconSelector + '.png' */
  386. };
  387. chrome.browserAction.setIcon({ tabId: tabId, path: iconPaths }, onIconReady);
  388. };
  389. /******************************************************************************/
  390. vAPI.messaging = {
  391. ports: {},
  392. listeners: {},
  393. defaultHandler: null,
  394. NOOPFUNC: noopFunc,
  395. UNHANDLED: 'vAPI.messaging.notHandled'
  396. };
  397. /******************************************************************************/
  398. vAPI.messaging.listen = function(listenerName, callback) {
  399. this.listeners[listenerName] = callback;
  400. };
  401. /******************************************************************************/
  402. vAPI.messaging.onPortMessage = function(request, port) {
  403. var callback = vAPI.messaging.NOOPFUNC;
  404. if ( request.requestId !== undefined ) {
  405. callback = CallbackWrapper.factory(port, request).callback;
  406. }
  407. // Specific handler
  408. var r = vAPI.messaging.UNHANDLED;
  409. var listener = vAPI.messaging.listeners[request.channelName];
  410. if ( typeof listener === 'function' ) {
  411. r = listener(request.msg, port.sender, callback);
  412. }
  413. if ( r !== vAPI.messaging.UNHANDLED ) {
  414. return;
  415. }
  416. // Default handler
  417. r = vAPI.messaging.defaultHandler(request.msg, port.sender, callback);
  418. if ( r !== vAPI.messaging.UNHANDLED ) {
  419. return;
  420. }
  421. console.error('µMatrix> messaging > unknown request: %o', request);
  422. // Unhandled:
  423. // Need to callback anyways in case caller expected an answer, or
  424. // else there is a memory leak on caller's side
  425. callback();
  426. };
  427. /******************************************************************************/
  428. vAPI.messaging.onPortDisconnect = function(port) {
  429. port.onDisconnect.removeListener(vAPI.messaging.onPortDisconnect);
  430. port.onMessage.removeListener(vAPI.messaging.onPortMessage);
  431. delete vAPI.messaging.ports[port.name];
  432. };
  433. /******************************************************************************/
  434. vAPI.messaging.onPortConnect = function(port) {
  435. port.onDisconnect.addListener(vAPI.messaging.onPortDisconnect);
  436. port.onMessage.addListener(vAPI.messaging.onPortMessage);
  437. vAPI.messaging.ports[port.name] = port;
  438. };
  439. /******************************************************************************/
  440. vAPI.messaging.setup = function(defaultHandler) {
  441. // Already setup?
  442. if ( this.defaultHandler !== null ) {
  443. return;
  444. }
  445. if ( typeof defaultHandler !== 'function' ) {
  446. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  447. }
  448. this.defaultHandler = defaultHandler;
  449. chrome.runtime.onConnect.addListener(this.onPortConnect);
  450. };
  451. /******************************************************************************/
  452. vAPI.messaging.broadcast = function(message) {
  453. var messageWrapper = {
  454. broadcast: true,
  455. msg: message
  456. };
  457. for ( var portName in this.ports ) {
  458. if ( this.ports.hasOwnProperty(portName) === false ) {
  459. continue;
  460. }
  461. this.ports[portName].postMessage(messageWrapper);
  462. }
  463. };
  464. /******************************************************************************/
  465. // This allows to avoid creating a closure for every single message which
  466. // expects an answer. Having a closure created each time a message is processed
  467. // has been always bothering me. Another benefit of the implementation here
  468. // is to reuse the callback proxy object, so less memory churning.
  469. //
  470. // https://developers.google.com/speed/articles/optimizing-javascript
  471. // "Creating a closure is significantly slower then creating an inner
  472. // function without a closure, and much slower than reusing a static
  473. // function"
  474. //
  475. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  476. // "the dreaded 'uniformly slow code' case where every function takes 1%
  477. // of CPU and you have to make one hundred separate performance optimizations
  478. // to improve performance at all"
  479. //
  480. // http://jsperf.com/closure-no-closure/2
  481. var CallbackWrapper = function(port, request) {
  482. // No need to bind every single time
  483. this.callback = this.proxy.bind(this);
  484. this.messaging = vAPI.messaging;
  485. this.init(port, request);
  486. };
  487. CallbackWrapper.junkyard = [];
  488. CallbackWrapper.factory = function(port, request) {
  489. var wrapper = CallbackWrapper.junkyard.pop();
  490. if ( wrapper ) {
  491. wrapper.init(port, request);
  492. return wrapper;
  493. }
  494. return new CallbackWrapper(port, request);
  495. };
  496. CallbackWrapper.prototype.init = function(port, request) {
  497. this.port = port;
  498. this.request = request;
  499. };
  500. CallbackWrapper.prototype.proxy = function(response) {
  501. // https://github.com/chrisaljoudi/uBlock/issues/383
  502. if ( this.messaging.ports.hasOwnProperty(this.port.name) ) {
  503. this.port.postMessage({
  504. requestId: this.request.requestId,
  505. channelName: this.request.channelName,
  506. msg: response !== undefined ? response : null
  507. });
  508. }
  509. // Mark for reuse
  510. this.port = this.request = null;
  511. CallbackWrapper.junkyard.push(this);
  512. };
  513. /******************************************************************************/
  514. vAPI.net = {};
  515. /******************************************************************************/
  516. vAPI.net.registerListeners = function() {
  517. var µm = µMatrix;
  518. var µmuri = µm.URI;
  519. var httpRequestHeadersJunkyard = [];
  520. // Abstraction layer to deal with request headers
  521. // >>>>>>>>
  522. var httpRequestHeadersFactory = function(headers) {
  523. var entry = httpRequestHeadersJunkyard.pop();
  524. if ( entry ) {
  525. return entry.init(headers);
  526. }
  527. return new HTTPRequestHeaders(headers);
  528. };
  529. var HTTPRequestHeaders = function(headers) {
  530. this.init(headers);
  531. };
  532. HTTPRequestHeaders.prototype.init = function(headers) {
  533. this.modified = false;
  534. this.headers = headers;
  535. return this;
  536. };
  537. HTTPRequestHeaders.prototype.dispose = function() {
  538. var r = this.modified ? this.headers : null;
  539. this.headers = null;
  540. httpRequestHeadersJunkyard.push(this);
  541. return r;
  542. };
  543. HTTPRequestHeaders.prototype.getHeader = function(target) {
  544. var headers = this.headers;
  545. var header, name;
  546. var i = headers.length;
  547. while ( i-- ) {
  548. header = headers[i];
  549. name = header.name.toLowerCase();
  550. if ( name === target ) {
  551. return header.value;
  552. }
  553. }
  554. return '';
  555. };
  556. HTTPRequestHeaders.prototype.setHeader = function(target, value, create) {
  557. var headers = this.headers;
  558. var header, name;
  559. var i = headers.length;
  560. while ( i-- ) {
  561. header = headers[i];
  562. name = header.name.toLowerCase();
  563. if ( name === target ) {
  564. break;
  565. }
  566. }
  567. if ( i < 0 && !create ) { // Header not found, don't add it
  568. return false;
  569. }
  570. if ( i < 0 ) { // Header not found, add it
  571. headers.push({ name: target, value: value });
  572. } else if ( value === '' ) { // Header found, remove it
  573. headers.splice(i, 1);
  574. } else { // Header found, modify it
  575. header.value = value;
  576. }
  577. this.modified = true;
  578. return true;
  579. };
  580. // <<<<<<<<
  581. // End of: Abstraction layer to deal with request headers
  582. // Normalizing request types
  583. // >>>>>>>>
  584. var normalizeRequestDetails = function(details) {
  585. µmuri.set(details.url);
  586. details.tabId = details.tabId.toString();
  587. details.hostname = µmuri.hostnameFromURI(details.url);
  588. // The rest of the function code is to normalize request type
  589. if ( details.type !== 'other' ) {
  590. return;
  591. }
  592. if ( details.requestHeaders instanceof HTTPRequestHeaders ) {
  593. if ( details.requestHeaders.getHeader('ping-to') !== '' ) {
  594. details.type = 'ping';
  595. return;
  596. }
  597. }
  598. var tail = µmuri.path.slice(-6);
  599. var pos = tail.lastIndexOf('.');
  600. // https://github.com/chrisaljoudi/uBlock/issues/862
  601. // If no transposition possible, transpose to `object` as per
  602. // Chromium bug 410382 (see below)
  603. if ( pos === -1 ) {
  604. return;
  605. }
  606. var ext = tail.slice(pos) + '.';
  607. if ( '.eot.ttf.otf.svg.woff.woff2.'.indexOf(ext) !== -1 ) {
  608. details.type = 'font';
  609. return;
  610. }
  611. // Still need this because often behind-the-scene requests are wrongly
  612. // categorized as 'other'
  613. if ( '.ico.png.gif.jpg.jpeg.webp.'.indexOf(ext) !== -1 ) {
  614. details.type = 'image';
  615. return;
  616. }
  617. };
  618. // <<<<<<<<
  619. // End of: Normalizing request types
  620. // Network event handlers
  621. // >>>>>>>>
  622. var onBeforeRequestClient = this.onBeforeRequest.callback;
  623. var onBeforeRequest = function(details) {
  624. normalizeRequestDetails(details);
  625. return onBeforeRequestClient(details);
  626. };
  627. chrome.webRequest.onBeforeRequest.addListener(
  628. onBeforeRequest,
  629. //function(details) {
  630. // quickProfiler.start('onBeforeRequest');
  631. // var r = onBeforeRequest(details);
  632. // quickProfiler.stop();
  633. // return r;
  634. //},
  635. {
  636. 'urls': this.onBeforeRequest.urls || ['<all_urls>'],
  637. 'types': this.onBeforeRequest.types || []
  638. },
  639. this.onBeforeRequest.extra
  640. );
  641. var onBeforeSendHeadersClient = this.onBeforeSendHeaders.callback;
  642. var onBeforeSendHeaders = function(details) {
  643. details.requestHeaders = httpRequestHeadersFactory(details.requestHeaders);
  644. normalizeRequestDetails(details);
  645. var result = onBeforeSendHeadersClient(details);
  646. if ( typeof result === 'object' ) {
  647. return result;
  648. }
  649. var modifiedHeaders = details.requestHeaders.dispose();
  650. if ( modifiedHeaders !== null ) {
  651. return { requestHeaders: modifiedHeaders };
  652. }
  653. };
  654. chrome.webRequest.onBeforeSendHeaders.addListener(
  655. onBeforeSendHeaders,
  656. {
  657. 'urls': this.onBeforeSendHeaders.urls || ['<all_urls>'],
  658. 'types': this.onBeforeSendHeaders.types || []
  659. },
  660. this.onBeforeSendHeaders.extra
  661. );
  662. var onHeadersReceivedClient = this.onHeadersReceived.callback;
  663. var onHeadersReceived = function(details) {
  664. normalizeRequestDetails(details);
  665. return onHeadersReceivedClient(details);
  666. };
  667. chrome.webRequest.onHeadersReceived.addListener(
  668. onHeadersReceived,
  669. {
  670. 'urls': this.onHeadersReceived.urls || ['<all_urls>'],
  671. 'types': this.onHeadersReceived.types || []
  672. },
  673. this.onHeadersReceived.extra
  674. );
  675. // <<<<<<<<
  676. // End of: Network event handlers
  677. };
  678. /******************************************************************************/
  679. vAPI.contextMenu = {
  680. create: function(details, callback) {
  681. this.menuId = details.id;
  682. this.callback = callback;
  683. chrome.contextMenus.create(details);
  684. chrome.contextMenus.onClicked.addListener(this.callback);
  685. },
  686. remove: function() {
  687. chrome.contextMenus.onClicked.removeListener(this.callback);
  688. chrome.contextMenus.remove(this.menuId);
  689. }
  690. };
  691. /******************************************************************************/
  692. vAPI.lastError = function() {
  693. return chrome.runtime.lastError;
  694. };
  695. /******************************************************************************/
  696. // This is called only once, when everything has been loaded in memory after
  697. // the extension was launched. It can be used to inject content scripts
  698. // in already opened web pages, to remove whatever nuisance could make it to
  699. // the web pages before uBlock was ready.
  700. vAPI.onLoadAllCompleted = function() {
  701. };
  702. /******************************************************************************/
  703. vAPI.punycodeHostname = function(hostname) {
  704. return hostname;
  705. };
  706. vAPI.punycodeURL = function(url) {
  707. return url;
  708. };
  709. /******************************************************************************/
  710. vAPI.browserCache = {};
  711. /******************************************************************************/
  712. vAPI.browserCache.clearByTime = function(since) {
  713. chrome.browsingData.removeCache({ since: 0 });
  714. };
  715. vAPI.browserCache.clearByOrigin = function(/* domain */) {
  716. // unsupported on Chromium
  717. };
  718. /******************************************************************************/
  719. vAPI.cookies = {};
  720. /******************************************************************************/
  721. vAPI.cookies.registerListeners = function() {
  722. if ( typeof this.onChanged === 'function' ) {
  723. chrome.cookies.onChanged.addListener(this.onChanged);
  724. }
  725. };
  726. /******************************************************************************/
  727. vAPI.cookies.getAll = function(callback) {
  728. chrome.cookies.getAll({}, callback);
  729. };
  730. /******************************************************************************/
  731. vAPI.cookies.remove = function(details, callback) {
  732. chrome.cookies.remove(details, callback || noopFunc);
  733. };
  734. /******************************************************************************/
  735. })();
  736. /******************************************************************************/