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.

922 lines
29 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
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. /******************************************************************************/
  391. vAPI.messaging = {
  392. ports: {},
  393. listeners: {},
  394. defaultHandler: null,
  395. NOOPFUNC: noopFunc,
  396. UNHANDLED: 'vAPI.messaging.notHandled'
  397. };
  398. /******************************************************************************/
  399. vAPI.messaging.listen = function(listenerName, callback) {
  400. this.listeners[listenerName] = callback;
  401. };
  402. /******************************************************************************/
  403. vAPI.messaging.onPortMessage = function(request, port) {
  404. var callback = vAPI.messaging.NOOPFUNC;
  405. if ( request.requestId !== undefined ) {
  406. callback = CallbackWrapper.factory(port, request).callback;
  407. }
  408. // Specific handler
  409. var r = vAPI.messaging.UNHANDLED;
  410. var listener = vAPI.messaging.listeners[request.channelName];
  411. if ( typeof listener === 'function' ) {
  412. r = listener(request.msg, port.sender, callback);
  413. }
  414. if ( r !== vAPI.messaging.UNHANDLED ) {
  415. return;
  416. }
  417. // Default handler
  418. r = vAPI.messaging.defaultHandler(request.msg, port.sender, callback);
  419. if ( r !== vAPI.messaging.UNHANDLED ) {
  420. return;
  421. }
  422. console.error('µMatrix> messaging > unknown request: %o', request);
  423. // Unhandled:
  424. // Need to callback anyways in case caller expected an answer, or
  425. // else there is a memory leak on caller's side
  426. callback();
  427. };
  428. /******************************************************************************/
  429. vAPI.messaging.onPortDisconnect = function(port) {
  430. port.onDisconnect.removeListener(vAPI.messaging.onPortDisconnect);
  431. port.onMessage.removeListener(vAPI.messaging.onPortMessage);
  432. delete vAPI.messaging.ports[port.name];
  433. };
  434. /******************************************************************************/
  435. vAPI.messaging.onPortConnect = function(port) {
  436. port.onDisconnect.addListener(vAPI.messaging.onPortDisconnect);
  437. port.onMessage.addListener(vAPI.messaging.onPortMessage);
  438. vAPI.messaging.ports[port.name] = port;
  439. };
  440. /******************************************************************************/
  441. vAPI.messaging.setup = function(defaultHandler) {
  442. // Already setup?
  443. if ( this.defaultHandler !== null ) {
  444. return;
  445. }
  446. if ( typeof defaultHandler !== 'function' ) {
  447. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  448. }
  449. this.defaultHandler = defaultHandler;
  450. chrome.runtime.onConnect.addListener(this.onPortConnect);
  451. };
  452. /******************************************************************************/
  453. vAPI.messaging.broadcast = function(message) {
  454. var messageWrapper = {
  455. broadcast: true,
  456. msg: message
  457. };
  458. for ( var portName in this.ports ) {
  459. if ( this.ports.hasOwnProperty(portName) === false ) {
  460. continue;
  461. }
  462. this.ports[portName].postMessage(messageWrapper);
  463. }
  464. };
  465. /******************************************************************************/
  466. // This allows to avoid creating a closure for every single message which
  467. // expects an answer. Having a closure created each time a message is processed
  468. // has been always bothering me. Another benefit of the implementation here
  469. // is to reuse the callback proxy object, so less memory churning.
  470. //
  471. // https://developers.google.com/speed/articles/optimizing-javascript
  472. // "Creating a closure is significantly slower then creating an inner
  473. // function without a closure, and much slower than reusing a static
  474. // function"
  475. //
  476. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  477. // "the dreaded 'uniformly slow code' case where every function takes 1%
  478. // of CPU and you have to make one hundred separate performance optimizations
  479. // to improve performance at all"
  480. //
  481. // http://jsperf.com/closure-no-closure/2
  482. var CallbackWrapper = function(port, request) {
  483. // No need to bind every single time
  484. this.callback = this.proxy.bind(this);
  485. this.messaging = vAPI.messaging;
  486. this.init(port, request);
  487. };
  488. CallbackWrapper.junkyard = [];
  489. CallbackWrapper.factory = function(port, request) {
  490. var wrapper = CallbackWrapper.junkyard.pop();
  491. if ( wrapper ) {
  492. wrapper.init(port, request);
  493. return wrapper;
  494. }
  495. return new CallbackWrapper(port, request);
  496. };
  497. CallbackWrapper.prototype.init = function(port, request) {
  498. this.port = port;
  499. this.request = request;
  500. };
  501. CallbackWrapper.prototype.proxy = function(response) {
  502. // https://github.com/chrisaljoudi/uBlock/issues/383
  503. if ( this.messaging.ports.hasOwnProperty(this.port.name) ) {
  504. this.port.postMessage({
  505. requestId: this.request.requestId,
  506. channelName: this.request.channelName,
  507. msg: response !== undefined ? response : null
  508. });
  509. }
  510. // Mark for reuse
  511. this.port = this.request = null;
  512. CallbackWrapper.junkyard.push(this);
  513. };
  514. /******************************************************************************/
  515. /******************************************************************************/
  516. vAPI.net = {};
  517. /******************************************************************************/
  518. vAPI.net.registerListeners = function() {
  519. var µm = µMatrix;
  520. var µmuri = µm.URI;
  521. var httpRequestHeadersJunkyard = [];
  522. // Abstraction layer to deal with request headers
  523. // >>>>>>>>
  524. var httpRequestHeadersFactory = function(headers) {
  525. var entry = httpRequestHeadersJunkyard.pop();
  526. if ( entry ) {
  527. return entry.init(headers);
  528. }
  529. return new HTTPRequestHeaders(headers);
  530. };
  531. var HTTPRequestHeaders = function(headers) {
  532. this.init(headers);
  533. };
  534. HTTPRequestHeaders.prototype.init = function(headers) {
  535. this.modified = false;
  536. this.headers = headers;
  537. return this;
  538. };
  539. HTTPRequestHeaders.prototype.dispose = function() {
  540. var r = this.modified ? this.headers : null;
  541. this.headers = null;
  542. httpRequestHeadersJunkyard.push(this);
  543. return r;
  544. };
  545. HTTPRequestHeaders.prototype.getHeader = function(target) {
  546. var headers = this.headers;
  547. var header, name;
  548. var i = headers.length;
  549. while ( i-- ) {
  550. header = headers[i];
  551. name = header.name.toLowerCase();
  552. if ( name === target ) {
  553. return header.value;
  554. }
  555. }
  556. return '';
  557. };
  558. HTTPRequestHeaders.prototype.setHeader = function(target, value, create) {
  559. var headers = this.headers;
  560. var header, name;
  561. var i = headers.length;
  562. while ( i-- ) {
  563. header = headers[i];
  564. name = header.name.toLowerCase();
  565. if ( name === target ) {
  566. break;
  567. }
  568. }
  569. if ( i < 0 && !create ) { // Header not found, don't add it
  570. return false;
  571. }
  572. if ( i < 0 ) { // Header not found, add it
  573. headers.push({ name: target, value: value });
  574. } else if ( value === '' ) { // Header found, remove it
  575. headers.splice(i, 1);
  576. } else { // Header found, modify it
  577. header.value = value;
  578. }
  579. this.modified = true;
  580. return true;
  581. };
  582. // <<<<<<<<
  583. // End of: Abstraction layer to deal with request headers
  584. // Normalizing request types
  585. // >>>>>>>>
  586. var normalizeRequestDetails = function(details) {
  587. µmuri.set(details.url);
  588. details.tabId = details.tabId.toString();
  589. details.hostname = µmuri.hostnameFromURI(details.url);
  590. // The rest of the function code is to normalize request type
  591. if ( details.type !== 'other' ) {
  592. return;
  593. }
  594. if ( details.requestHeaders instanceof HTTPRequestHeaders ) {
  595. if ( details.requestHeaders.getHeader('ping-to') !== '' ) {
  596. details.type = 'ping';
  597. return;
  598. }
  599. }
  600. var tail = µmuri.path.slice(-6);
  601. var pos = tail.lastIndexOf('.');
  602. // https://github.com/chrisaljoudi/uBlock/issues/862
  603. // If no transposition possible, transpose to `object` as per
  604. // Chromium bug 410382 (see below)
  605. if ( pos === -1 ) {
  606. return;
  607. }
  608. var ext = tail.slice(pos) + '.';
  609. if ( '.eot.ttf.otf.svg.woff.woff2.'.indexOf(ext) !== -1 ) {
  610. details.type = 'font';
  611. return;
  612. }
  613. // Still need this because often behind-the-scene requests are wrongly
  614. // categorized as 'other'
  615. if ( '.ico.png.gif.jpg.jpeg.webp.'.indexOf(ext) !== -1 ) {
  616. details.type = 'image';
  617. return;
  618. }
  619. };
  620. // <<<<<<<<
  621. // End of: Normalizing request types
  622. // Network event handlers
  623. // >>>>>>>>
  624. var onBeforeRequestClient = this.onBeforeRequest.callback;
  625. var onBeforeRequest = function(details) {
  626. normalizeRequestDetails(details);
  627. return onBeforeRequestClient(details);
  628. };
  629. chrome.webRequest.onBeforeRequest.addListener(
  630. onBeforeRequest,
  631. //function(details) {
  632. // quickProfiler.start('onBeforeRequest');
  633. // var r = onBeforeRequest(details);
  634. // quickProfiler.stop();
  635. // return r;
  636. //},
  637. {
  638. 'urls': this.onBeforeRequest.urls || ['<all_urls>'],
  639. 'types': this.onBeforeRequest.types || []
  640. },
  641. this.onBeforeRequest.extra
  642. );
  643. var onBeforeSendHeadersClient = this.onBeforeSendHeaders.callback;
  644. var onBeforeSendHeaders = function(details) {
  645. details.requestHeaders = httpRequestHeadersFactory(details.requestHeaders);
  646. normalizeRequestDetails(details);
  647. var result = onBeforeSendHeadersClient(details);
  648. if ( typeof result === 'object' ) {
  649. return result;
  650. }
  651. var modifiedHeaders = details.requestHeaders.dispose();
  652. if ( modifiedHeaders !== null ) {
  653. return { requestHeaders: modifiedHeaders };
  654. }
  655. };
  656. chrome.webRequest.onBeforeSendHeaders.addListener(
  657. onBeforeSendHeaders,
  658. {
  659. 'urls': this.onBeforeSendHeaders.urls || ['<all_urls>'],
  660. 'types': this.onBeforeSendHeaders.types || []
  661. },
  662. this.onBeforeSendHeaders.extra
  663. );
  664. var onHeadersReceivedClient = this.onHeadersReceived.callback;
  665. var onHeadersReceived = function(details) {
  666. normalizeRequestDetails(details);
  667. return onHeadersReceivedClient(details);
  668. };
  669. chrome.webRequest.onHeadersReceived.addListener(
  670. onHeadersReceived,
  671. {
  672. 'urls': this.onHeadersReceived.urls || ['<all_urls>'],
  673. 'types': this.onHeadersReceived.types || []
  674. },
  675. this.onHeadersReceived.extra
  676. );
  677. // <<<<<<<<
  678. // End of: Network event handlers
  679. };
  680. /******************************************************************************/
  681. /******************************************************************************/
  682. vAPI.contextMenu = {
  683. create: function(details, callback) {
  684. this.menuId = details.id;
  685. this.callback = callback;
  686. chrome.contextMenus.create(details);
  687. chrome.contextMenus.onClicked.addListener(this.callback);
  688. },
  689. remove: function() {
  690. chrome.contextMenus.onClicked.removeListener(this.callback);
  691. chrome.contextMenus.remove(this.menuId);
  692. }
  693. };
  694. /******************************************************************************/
  695. vAPI.lastError = function() {
  696. return chrome.runtime.lastError;
  697. };
  698. /******************************************************************************/
  699. /******************************************************************************/
  700. // This is called only once, when everything has been loaded in memory after
  701. // the extension was launched. It can be used to inject content scripts
  702. // in already opened web pages, to remove whatever nuisance could make it to
  703. // the web pages before uBlock was ready.
  704. vAPI.onLoadAllCompleted = function() {
  705. };
  706. /******************************************************************************/
  707. /******************************************************************************/
  708. vAPI.punycodeHostname = function(hostname) {
  709. return hostname;
  710. };
  711. vAPI.punycodeURL = function(url) {
  712. return url;
  713. };
  714. /******************************************************************************/
  715. /******************************************************************************/
  716. vAPI.browserData = {};
  717. /******************************************************************************/
  718. // https://developer.chrome.com/extensions/browsingData
  719. vAPI.browserData.clearCache = function(callback) {
  720. chrome.browsingData.removeCache({ since: 0 }, callback);
  721. };
  722. /******************************************************************************/
  723. // Not supported on Chromium
  724. vAPI.browserData.clearOrigin = function(domain, callback) {
  725. // unsupported on Chromium
  726. if ( typeof callback === 'function' ) {
  727. callback(undefined);
  728. }
  729. };
  730. /******************************************************************************/
  731. /******************************************************************************/
  732. // https://developer.chrome.com/extensions/cookies
  733. vAPI.cookies = {};
  734. /******************************************************************************/
  735. vAPI.cookies.start = function() {
  736. var onChanged = function(changeInfo) {
  737. var handler = changeInfo.removed ? this.onRemoved : this.onChanged;
  738. if ( typeof handler !== 'function' ) {
  739. return;
  740. }
  741. handler(changeInfo.cookie);
  742. };
  743. chrome.cookies.onChanged.addListener(onChanged.bind(this));
  744. };
  745. /******************************************************************************/
  746. vAPI.cookies.getAll = function(callback) {
  747. chrome.cookies.getAll({}, callback);
  748. };
  749. /******************************************************************************/
  750. vAPI.cookies.remove = function(details, callback) {
  751. chrome.cookies.remove(details, callback || noopFunc);
  752. };
  753. /******************************************************************************/
  754. /******************************************************************************/
  755. })();
  756. /******************************************************************************/