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.

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