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.

450 lines
14 KiB

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