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.

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