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.

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