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.

484 lines
15 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
  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. /******************************************************************************/
  27. vAPI.app = {
  28. name: manifest.name,
  29. version: manifest.version
  30. };
  31. /******************************************************************************/
  32. vAPI.app.restart = function() {
  33. chrome.runtime.reload();
  34. };
  35. /******************************************************************************/
  36. vAPI.storage = chrome.storage.local;
  37. /******************************************************************************/
  38. vAPI.tabs = {};
  39. /******************************************************************************/
  40. vAPI.tabs.registerListeners = function() {
  41. if ( typeof this.onNavigation === 'function' ) {
  42. chrome.webNavigation.onCommitted.addListener(this.onNavigation);
  43. }
  44. if ( typeof this.onUpdated === 'function' ) {
  45. chrome.tabs.onUpdated.addListener(this.onUpdated);
  46. }
  47. if ( typeof this.onClosed === 'function' ) {
  48. chrome.tabs.onRemoved.addListener(this.onClosed);
  49. }
  50. if ( typeof this.onPopup === 'function' ) {
  51. chrome.webNavigation.onCreatedNavigationTarget.addListener(this.onPopup);
  52. }
  53. };
  54. /******************************************************************************/
  55. vAPI.tabs.get = function(tabId, callback) {
  56. var onTabReady = function(tab) {
  57. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  58. if ( chrome.runtime.lastError ) {
  59. ;
  60. }
  61. // Caller must be prepared to deal with nil tab value
  62. callback(tab);
  63. };
  64. if ( tabId !== null ) {
  65. if ( typeof tabId === 'string' ) {
  66. tabId = parseInt(tabId, 10);
  67. }
  68. chrome.tabs.get(tabId, onTabReady);
  69. return;
  70. }
  71. var onTabReceived = function(tabs) {
  72. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  73. if ( chrome.runtime.lastError ) {
  74. ;
  75. }
  76. callback(tabs[0]);
  77. };
  78. chrome.tabs.query({ active: true, currentWindow: true }, onTabReceived);
  79. };
  80. /******************************************************************************/
  81. // properties of the details object:
  82. // url: 'URL', // the address that will be opened
  83. // tabId: 1, // the tab is used if set, instead of creating a new one
  84. // index: -1, // undefined: end of the list, -1: following tab, or after index
  85. // active: false, // opens the tab in background - true and undefined: foreground
  86. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  87. vAPI.tabs.open = function(details) {
  88. var targetURL = details.url;
  89. if ( typeof targetURL !== 'string' || targetURL === '' ) {
  90. return null;
  91. }
  92. // extension pages
  93. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  94. targetURL = vAPI.getURL(targetURL);
  95. }
  96. // dealing with Chrome's asynchronous API
  97. var wrapper = function() {
  98. if ( details.active === undefined ) {
  99. details.active = true;
  100. }
  101. var subWrapper = function() {
  102. var _details = {
  103. url: targetURL,
  104. active: !!details.active
  105. };
  106. if ( details.tabId ) {
  107. details.tabId = parseInt(tabId, 10);
  108. // update doesn't accept index, must use move
  109. chrome.tabs.update(details.tabId, _details, function(tab) {
  110. // if the tab doesn't exist
  111. if ( vAPI.lastError() ) {
  112. chrome.tabs.create(_details);
  113. } else if ( details.index !== undefined ) {
  114. chrome.tabs.move(tab.id, {index: details.index});
  115. }
  116. });
  117. } else {
  118. if ( details.index !== undefined ) {
  119. _details.index = details.index;
  120. }
  121. chrome.tabs.create(_details);
  122. }
  123. };
  124. if ( details.index === -1 ) {
  125. vAPI.tabs.get(null, function(tab) {
  126. if ( tab ) {
  127. details.index = tab.index + 1;
  128. } else {
  129. delete details.index;
  130. }
  131. subWrapper();
  132. });
  133. }
  134. else {
  135. subWrapper();
  136. }
  137. };
  138. if ( details.select ) {
  139. chrome.tabs.query({ currentWindow: true }, function(tabs) {
  140. var rgxHash = /#.*/;
  141. // this is questionable
  142. var url = targetURL.replace(rgxHash, '');
  143. var selected = tabs.some(function(tab) {
  144. if ( tab.url.replace(rgxHash, '') === url ) {
  145. chrome.tabs.update(tab.id, { active: true });
  146. return true;
  147. }
  148. });
  149. if ( !selected ) {
  150. wrapper();
  151. }
  152. });
  153. }
  154. else {
  155. wrapper();
  156. }
  157. };
  158. /******************************************************************************/
  159. vAPI.tabs.remove = function(tabId) {
  160. var onTabRemoved = function() {
  161. if ( vAPI.lastError() ) {
  162. }
  163. };
  164. chrome.tabs.remove(parseInt(tabId, 10), onTabRemoved);
  165. };
  166. /******************************************************************************/
  167. vAPI.tabs.reload = function(tabId, flags) {
  168. if ( typeof tabId === 'string' ) {
  169. tabId = parseInt(tabId, 10);
  170. }
  171. chrome.tabs.reload(tabId);
  172. };
  173. /******************************************************************************/
  174. vAPI.tabs.injectScript = function(tabId, details, callback) {
  175. var onScriptExecuted = function() {
  176. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  177. if ( chrome.runtime.lastError ) {
  178. }
  179. if ( typeof callback === 'function' ) {
  180. callback();
  181. }
  182. };
  183. if ( tabId ) {
  184. tabId = parseInt(tabId, 10);
  185. chrome.tabs.executeScript(tabId, details, onScriptExecuted);
  186. } else {
  187. chrome.tabs.executeScript(details, onScriptExecuted);
  188. }
  189. };
  190. /******************************************************************************/
  191. // Must read: https://code.google.com/p/chromium/issues/detail?id=410868#c8
  192. // https://github.com/gorhill/uBlock/issues/19
  193. // https://github.com/gorhill/uBlock/issues/207
  194. // Since we may be called asynchronously, the tab id may not exist
  195. // anymore, so this ensures it does still exist.
  196. vAPI.setIcon = function(tabId, iconStatus, badge) {
  197. tabId = parseInt(tabId, 10);
  198. var onIconReady = function() {
  199. if ( vAPI.lastError() ) {
  200. return;
  201. }
  202. chrome.browserAction.setBadgeText({ tabId: tabId, text: badge });
  203. if ( badge !== '' ) {
  204. chrome.browserAction.setBadgeBackgroundColor({
  205. tabId: tabId,
  206. color: '#666'
  207. });
  208. }
  209. };
  210. var iconPaths = iconStatus === 'on' ?
  211. { '19': 'img/browsericons/icon19.png', '38': 'img/browsericons/icon38.png' } :
  212. { '19': 'img/browsericons/icon19-off.png', '38': 'img/browsericons/icon38-off.png' };
  213. chrome.browserAction.setIcon({ tabId: tabId, path: iconPaths }, onIconReady);
  214. };
  215. /******************************************************************************/
  216. vAPI.messaging = {
  217. ports: {},
  218. listeners: {},
  219. defaultHandler: null,
  220. NOOPFUNC: function(){},
  221. UNHANDLED: 'vAPI.messaging.notHandled'
  222. };
  223. /******************************************************************************/
  224. vAPI.messaging.listen = function(listenerName, callback) {
  225. this.listeners[listenerName] = callback;
  226. };
  227. /******************************************************************************/
  228. vAPI.messaging.onPortMessage = function(request, port) {
  229. var callback = vAPI.messaging.NOOPFUNC;
  230. if ( request.requestId !== undefined ) {
  231. callback = function(response) {
  232. // https://github.com/gorhill/uBlock/issues/383
  233. if ( vAPI.messaging.ports.hasOwnProperty(port.name) === false ) {
  234. return;
  235. }
  236. port.postMessage({
  237. requestId: request.requestId,
  238. channelName: request.channelName,
  239. msg: response !== undefined ? response : null
  240. });
  241. };
  242. }
  243. // Specific handler
  244. var r = vAPI.messaging.UNHANDLED;
  245. var listener = vAPI.messaging.listeners[request.channelName];
  246. if ( typeof listener === 'function' ) {
  247. r = listener(request.msg, port.sender, callback);
  248. }
  249. if ( r !== vAPI.messaging.UNHANDLED ) {
  250. return;
  251. }
  252. // Default handler
  253. r = vAPI.messaging.defaultHandler(request.msg, port.sender, callback);
  254. if ( r !== vAPI.messaging.UNHANDLED ) {
  255. return;
  256. }
  257. console.error('µBlock> messaging > unknown request: %o', request);
  258. // Unhandled:
  259. // Need to callback anyways in case caller expected an answer, or
  260. // else there is a memory leak on caller's side
  261. callback();
  262. };
  263. /******************************************************************************/
  264. vAPI.messaging.onPortDisconnect = function(port) {
  265. port.onDisconnect.removeListener(vAPI.messaging.onPortDisconnect);
  266. port.onMessage.removeListener(vAPI.messaging.onPortMessage);
  267. delete vAPI.messaging.ports[port.name];
  268. };
  269. /******************************************************************************/
  270. vAPI.messaging.onPortConnect = function(port) {
  271. port.onDisconnect.addListener(vAPI.messaging.onPortDisconnect);
  272. port.onMessage.addListener(vAPI.messaging.onPortMessage);
  273. vAPI.messaging.ports[port.name] = port;
  274. };
  275. /******************************************************************************/
  276. vAPI.messaging.setup = function(defaultHandler) {
  277. // Already setup?
  278. if ( this.defaultHandler !== null ) {
  279. return;
  280. }
  281. if ( typeof defaultHandler !== 'function' ) {
  282. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  283. }
  284. this.defaultHandler = defaultHandler;
  285. chrome.runtime.onConnect.addListener(this.onPortConnect);
  286. };
  287. /******************************************************************************/
  288. vAPI.messaging.broadcast = function(message) {
  289. var messageWrapper = {
  290. broadcast: true,
  291. msg: message
  292. };
  293. for ( var portName in this.ports ) {
  294. if ( this.ports.hasOwnProperty(portName) === false ) {
  295. continue;
  296. }
  297. this.ports[portName].postMessage(messageWrapper);
  298. }
  299. };
  300. /******************************************************************************/
  301. vAPI.net = {
  302. registerListeners: function() {
  303. var listeners = [
  304. 'onBeforeRequest',
  305. 'onBeforeSendHeaders',
  306. 'onHeadersReceived'
  307. ];
  308. for ( var i = 0; i < listeners.length; i++ ) {
  309. chrome.webRequest[listeners[i]].addListener(
  310. this[listeners[i]].callback,
  311. {
  312. 'urls': this[listeners[i]].urls || ['<all_urls>'],
  313. 'types': this[listeners[i]].types || []
  314. },
  315. this[listeners[i]].extra
  316. );
  317. }
  318. }
  319. };
  320. /******************************************************************************/
  321. vAPI.contextMenu = {
  322. create: function(details, callback) {
  323. this.menuId = details.id;
  324. this.callback = callback;
  325. chrome.contextMenus.create(details);
  326. chrome.contextMenus.onClicked.addListener(this.callback);
  327. },
  328. remove: function() {
  329. chrome.contextMenus.onClicked.removeListener(this.callback);
  330. chrome.contextMenus.remove(this.menuId);
  331. }
  332. };
  333. /******************************************************************************/
  334. vAPI.lastError = function() {
  335. return chrome.runtime.lastError;
  336. };
  337. /******************************************************************************/
  338. // This is called only once, when everything has been loaded in memory after
  339. // the extension was launched. It can be used to inject content scripts
  340. // in already opened web pages, to remove whatever nuisance could make it to
  341. // the web pages before uBlock was ready.
  342. vAPI.onLoadAllCompleted = function() {
  343. // http://code.google.com/p/chromium/issues/detail?id=410868#c11
  344. // Need to be sure to access `vAPI.lastError()` to prevent
  345. // spurious warnings in the console.
  346. var scriptDone = function() {
  347. vAPI.lastError();
  348. };
  349. var scriptEnd = function(tabId) {
  350. if ( vAPI.lastError() ) {
  351. return;
  352. }
  353. vAPI.tabs.injectScript(tabId, {
  354. file: 'js/contentscript-end.js',
  355. allFrames: true,
  356. runAt: 'document_idle'
  357. }, scriptDone);
  358. };
  359. var scriptStart = function(tabId) {
  360. vAPI.tabs.injectScript(tabId, {
  361. file: 'js/vapi-client.js',
  362. allFrames: true,
  363. runAt: 'document_start'
  364. }, function(){ });
  365. vAPI.tabs.injectScript(tabId, {
  366. file: 'js/contentscript-start.js',
  367. allFrames: true,
  368. runAt: 'document_start'
  369. }, function(){ scriptEnd(tabId); });
  370. };
  371. var bindToTabs = function(tabs) {
  372. var µb = µBlock;
  373. var i = tabs.length, tab;
  374. while ( i-- ) {
  375. tab = tabs[i];
  376. µb.bindTabToPageStats(tab.id, tab.url);
  377. // https://github.com/gorhill/uBlock/issues/129
  378. scriptStart(tab.id);
  379. }
  380. };
  381. chrome.tabs.query({ url: 'http://*/*' }, bindToTabs);
  382. chrome.tabs.query({ url: 'https://*/*' }, bindToTabs);
  383. };
  384. /******************************************************************************/
  385. vAPI.punycodeHostname = function(hostname) {
  386. return hostname;
  387. };
  388. vAPI.punycodeURL = function(url) {
  389. return url;
  390. };
  391. /******************************************************************************/
  392. })();
  393. /******************************************************************************/