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.

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