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.

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