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.

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