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.

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