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.

551 lines
17 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
  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 = function(response) {
  237. // https://github.com/gorhill/uBlock/issues/383
  238. if ( vAPI.messaging.ports.hasOwnProperty(port.name) === false ) {
  239. return;
  240. }
  241. port.postMessage({
  242. requestId: request.requestId,
  243. channelName: request.channelName,
  244. msg: response !== undefined ? response : null
  245. });
  246. };
  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. vAPI.net = {};
  307. /******************************************************************************/
  308. vAPI.net.registerListeners = function() {
  309. var µb = µBlock;
  310. var µburi = µb.URI;
  311. var normalizeRequestDetails = function(details) {
  312. µburi.set(details.url);
  313. details.tabId = details.tabId.toString();
  314. details.hostname = µburi.hostnameFromURI(details.url);
  315. // The rest of the function code is to normalize type
  316. var type = details.type;
  317. if ( type !== 'other' ) {
  318. return;
  319. }
  320. var path = µburi.path;
  321. var pos = path.lastIndexOf('.');
  322. if ( pos === -1 ) {
  323. return;
  324. }
  325. var ext = path.slice(pos) + '.';
  326. if ( '.eot.ttf.otf.svg.woff.woff2.'.indexOf(ext) !== -1 ) {
  327. details.type = 'font';
  328. return;
  329. }
  330. // Still need this because often behind-the-scene requests are wrongly
  331. // categorized as 'other'
  332. if ( '.ico.png.gif.jpg.jpeg.webp.'.indexOf(ext) !== -1 ) {
  333. details.type = 'image';
  334. return;
  335. }
  336. // https://code.google.com/p/chromium/issues/detail?id=410382
  337. if ( type === 'other' ) {
  338. details.type = 'object';
  339. return;
  340. }
  341. };
  342. var onBeforeRequestClient = this.onBeforeRequest.callback;
  343. var onBeforeRequest = function(details) {
  344. normalizeRequestDetails(details);
  345. return onBeforeRequestClient(details);
  346. };
  347. chrome.webRequest.onBeforeRequest.addListener(
  348. onBeforeRequest,
  349. {
  350. 'urls': this.onBeforeRequest.urls || ['<all_urls>'],
  351. 'types': this.onBeforeRequest.types || []
  352. },
  353. this.onBeforeRequest.extra
  354. );
  355. chrome.webRequest.onBeforeSendHeaders.addListener(
  356. this.onBeforeSendHeaders.callback,
  357. {
  358. 'urls': this.onBeforeSendHeaders.urls || ['<all_urls>'],
  359. 'types': this.onBeforeSendHeaders.types || []
  360. },
  361. this.onBeforeSendHeaders.extra
  362. );
  363. var onHeadersReceivedClient = this.onHeadersReceived.callback;
  364. var onHeadersReceived = function(details) {
  365. normalizeRequestDetails(details);
  366. return onHeadersReceivedClient(details);
  367. };
  368. chrome.webRequest.onHeadersReceived.addListener(
  369. onHeadersReceived,
  370. {
  371. 'urls': this.onHeadersReceived.urls || ['<all_urls>'],
  372. 'types': this.onHeadersReceived.types || []
  373. },
  374. this.onHeadersReceived.extra
  375. );
  376. };
  377. /******************************************************************************/
  378. vAPI.contextMenu = {
  379. create: function(details, callback) {
  380. this.menuId = details.id;
  381. this.callback = callback;
  382. chrome.contextMenus.create(details);
  383. chrome.contextMenus.onClicked.addListener(this.callback);
  384. },
  385. remove: function() {
  386. chrome.contextMenus.onClicked.removeListener(this.callback);
  387. chrome.contextMenus.remove(this.menuId);
  388. }
  389. };
  390. /******************************************************************************/
  391. vAPI.lastError = function() {
  392. return chrome.runtime.lastError;
  393. };
  394. /******************************************************************************/
  395. // This is called only once, when everything has been loaded in memory after
  396. // the extension was launched. It can be used to inject content scripts
  397. // in already opened web pages, to remove whatever nuisance could make it to
  398. // the web pages before uBlock was ready.
  399. vAPI.onLoadAllCompleted = function() {
  400. // http://code.google.com/p/chromium/issues/detail?id=410868#c11
  401. // Need to be sure to access `vAPI.lastError()` to prevent
  402. // spurious warnings in the console.
  403. var scriptDone = function() {
  404. vAPI.lastError();
  405. };
  406. var scriptEnd = function(tabId) {
  407. if ( vAPI.lastError() ) {
  408. return;
  409. }
  410. vAPI.tabs.injectScript(tabId, {
  411. file: 'js/contentscript-end.js',
  412. allFrames: true,
  413. runAt: 'document_idle'
  414. }, scriptDone);
  415. };
  416. var scriptStart = function(tabId) {
  417. vAPI.tabs.injectScript(tabId, {
  418. file: 'js/vapi-client.js',
  419. allFrames: true,
  420. runAt: 'document_start'
  421. }, function(){ });
  422. vAPI.tabs.injectScript(tabId, {
  423. file: 'js/contentscript-start.js',
  424. allFrames: true,
  425. runAt: 'document_start'
  426. }, function(){ scriptEnd(tabId); });
  427. };
  428. var bindToTabs = function(tabs) {
  429. var µb = µBlock;
  430. var i = tabs.length, tab;
  431. while ( i-- ) {
  432. tab = tabs[i];
  433. µb.bindTabToPageStats(tab.id, tab.url);
  434. // https://github.com/gorhill/uBlock/issues/129
  435. scriptStart(tab.id);
  436. }
  437. };
  438. chrome.tabs.query({ url: 'http://*/*' }, bindToTabs);
  439. chrome.tabs.query({ url: 'https://*/*' }, bindToTabs);
  440. };
  441. /******************************************************************************/
  442. vAPI.punycodeHostname = function(hostname) {
  443. return hostname;
  444. };
  445. vAPI.punycodeURL = function(url) {
  446. return url;
  447. };
  448. /******************************************************************************/
  449. })();
  450. /******************************************************************************/