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.

603 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
  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. if ( pos === -1 ) {
  362. return;
  363. }
  364. var ext = path.slice(pos) + '.';
  365. if ( '.eot.ttf.otf.svg.woff.woff2.'.indexOf(ext) !== -1 ) {
  366. details.type = 'font';
  367. return;
  368. }
  369. // Still need this because often behind-the-scene requests are wrongly
  370. // categorized as 'other'
  371. if ( '.ico.png.gif.jpg.jpeg.webp.'.indexOf(ext) !== -1 ) {
  372. details.type = 'image';
  373. return;
  374. }
  375. // https://code.google.com/p/chromium/issues/detail?id=410382
  376. if ( type === 'other' ) {
  377. details.type = 'object';
  378. return;
  379. }
  380. };
  381. var onBeforeRequestClient = this.onBeforeRequest.callback;
  382. var onBeforeRequest = function(details) {
  383. normalizeRequestDetails(details);
  384. return onBeforeRequestClient(details);
  385. };
  386. chrome.webRequest.onBeforeRequest.addListener(
  387. onBeforeRequest,
  388. //function(details) {
  389. // quickProfiler.start('onBeforeRequest');
  390. // var r = onBeforeRequest(details);
  391. // quickProfiler.stop();
  392. // return r;
  393. //},
  394. {
  395. 'urls': this.onBeforeRequest.urls || ['<all_urls>'],
  396. 'types': this.onBeforeRequest.types || []
  397. },
  398. this.onBeforeRequest.extra
  399. );
  400. chrome.webRequest.onBeforeSendHeaders.addListener(
  401. this.onBeforeSendHeaders.callback,
  402. {
  403. 'urls': this.onBeforeSendHeaders.urls || ['<all_urls>'],
  404. 'types': this.onBeforeSendHeaders.types || []
  405. },
  406. this.onBeforeSendHeaders.extra
  407. );
  408. var onHeadersReceivedClient = this.onHeadersReceived.callback;
  409. var onHeadersReceived = function(details) {
  410. normalizeRequestDetails(details);
  411. return onHeadersReceivedClient(details);
  412. };
  413. chrome.webRequest.onHeadersReceived.addListener(
  414. onHeadersReceived,
  415. {
  416. 'urls': this.onHeadersReceived.urls || ['<all_urls>'],
  417. 'types': this.onHeadersReceived.types || []
  418. },
  419. this.onHeadersReceived.extra
  420. );
  421. };
  422. /******************************************************************************/
  423. vAPI.contextMenu = {
  424. create: function(details, callback) {
  425. this.menuId = details.id;
  426. this.callback = callback;
  427. chrome.contextMenus.create(details);
  428. chrome.contextMenus.onClicked.addListener(this.callback);
  429. },
  430. remove: function() {
  431. chrome.contextMenus.onClicked.removeListener(this.callback);
  432. chrome.contextMenus.remove(this.menuId);
  433. }
  434. };
  435. /******************************************************************************/
  436. vAPI.lastError = function() {
  437. return chrome.runtime.lastError;
  438. };
  439. /******************************************************************************/
  440. // This is called only once, when everything has been loaded in memory after
  441. // the extension was launched. It can be used to inject content scripts
  442. // in already opened web pages, to remove whatever nuisance could make it to
  443. // the web pages before uBlock was ready.
  444. vAPI.onLoadAllCompleted = function() {
  445. // http://code.google.com/p/chromium/issues/detail?id=410868#c11
  446. // Need to be sure to access `vAPI.lastError()` to prevent
  447. // spurious warnings in the console.
  448. var scriptDone = function() {
  449. vAPI.lastError();
  450. };
  451. var scriptEnd = function(tabId) {
  452. if ( vAPI.lastError() ) {
  453. return;
  454. }
  455. vAPI.tabs.injectScript(tabId, {
  456. file: 'js/contentscript-end.js',
  457. allFrames: true,
  458. runAt: 'document_idle'
  459. }, scriptDone);
  460. };
  461. var scriptStart = function(tabId) {
  462. vAPI.tabs.injectScript(tabId, {
  463. file: 'js/vapi-client.js',
  464. allFrames: true,
  465. runAt: 'document_start'
  466. }, function(){ });
  467. vAPI.tabs.injectScript(tabId, {
  468. file: 'js/contentscript-start.js',
  469. allFrames: true,
  470. runAt: 'document_start'
  471. }, function(){ scriptEnd(tabId); });
  472. };
  473. var bindToTabs = function(tabs) {
  474. var µb = µBlock;
  475. var i = tabs.length, tab;
  476. while ( i-- ) {
  477. tab = tabs[i];
  478. µb.bindTabToPageStats(tab.id, tab.url);
  479. // https://github.com/gorhill/uBlock/issues/129
  480. scriptStart(tab.id);
  481. }
  482. };
  483. chrome.tabs.query({ url: 'http://*/*' }, bindToTabs);
  484. chrome.tabs.query({ url: 'https://*/*' }, bindToTabs);
  485. };
  486. /******************************************************************************/
  487. vAPI.punycodeHostname = function(hostname) {
  488. return hostname;
  489. };
  490. vAPI.punycodeURL = function(url) {
  491. return url;
  492. };
  493. /******************************************************************************/
  494. })();
  495. /******************************************************************************/