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.

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