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.

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