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.

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