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.

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