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.

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