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.

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