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.

463 lines
14 KiB

10 years ago
10 years ago
10 years ago
10 years ago
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. ;
  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. // 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(tabId, 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. chrome.tabs.executeScript(tabId, details, onScriptExecuted);
  185. } else {
  186. chrome.tabs.executeScript(details, onScriptExecuted);
  187. }
  188. };
  189. /******************************************************************************/
  190. // Must read: https://code.google.com/p/chromium/issues/detail?id=410868#c8
  191. // https://github.com/gorhill/uBlock/issues/19
  192. // https://github.com/gorhill/uBlock/issues/207
  193. // Since we may be called asynchronously, the tab id may not exist
  194. // anymore, so this ensures it does still exist.
  195. vAPI.setIcon = function(tabId, img, badge) {
  196. var onIconReady = function() {
  197. if ( vAPI.lastError() ) {
  198. return;
  199. }
  200. chrome.browserAction.setBadgeText({ tabId: tabId, text: badge });
  201. if ( badge !== '' ) {
  202. chrome.browserAction.setBadgeBackgroundColor({ tabId: tabId, color: '#666' });
  203. }
  204. };
  205. chrome.browserAction.setIcon({ tabId: tabId, path: img }, onIconReady);
  206. };
  207. /******************************************************************************/
  208. vAPI.messaging = {
  209. ports: {},
  210. listeners: {},
  211. defaultHandler: null,
  212. NOOPFUNC: function(){},
  213. UNHANDLED: 'vAPI.messaging.notHandled'
  214. };
  215. /******************************************************************************/
  216. vAPI.messaging.listen = function(listenerName, callback) {
  217. this.listeners[listenerName] = callback;
  218. };
  219. /******************************************************************************/
  220. vAPI.messaging.onPortMessage = function(request, port) {
  221. var callback = vAPI.messaging.NOOPFUNC;
  222. if ( request.requestId !== undefined ) {
  223. callback = function(response) {
  224. // https://github.com/gorhill/uBlock/issues/383
  225. if ( vAPI.messaging.ports.hasOwnProperty(port.name) === false ) {
  226. return;
  227. }
  228. port.postMessage({
  229. requestId: request.requestId,
  230. portName: request.portName,
  231. msg: response !== undefined ? response : null
  232. });
  233. };
  234. }
  235. // Specific handler
  236. var r = vAPI.messaging.UNHANDLED;
  237. var listener = vAPI.messaging.listeners[request.portName];
  238. if ( typeof listener === 'function' ) {
  239. r = listener(request.msg, port.sender, callback);
  240. }
  241. if ( r !== vAPI.messaging.UNHANDLED ) {
  242. return;
  243. }
  244. // Default handler
  245. r = vAPI.messaging.defaultHandler(request.msg, port.sender, callback);
  246. if ( r !== vAPI.messaging.UNHANDLED ) {
  247. return;
  248. }
  249. console.error('µBlock> messaging > unknown request: %o', request);
  250. // Unhandled:
  251. // Need to callback anyways in case caller expected an answer, or
  252. // else there is a memory leak on caller's side
  253. callback();
  254. };
  255. /******************************************************************************/
  256. vAPI.messaging.onPortDisconnect = function(port) {
  257. port.onDisconnect.removeListener(vAPI.messaging.onPortDisconnect);
  258. port.onMessage.removeListener(vAPI.messaging.onPortMessage);
  259. delete vAPI.messaging.ports[port.name];
  260. };
  261. /******************************************************************************/
  262. vAPI.messaging.onPortConnect = function(port) {
  263. port.onDisconnect.addListener(vAPI.messaging.onPortDisconnect);
  264. port.onMessage.addListener(vAPI.messaging.onPortMessage);
  265. vAPI.messaging.ports[port.name] = port;
  266. };
  267. /******************************************************************************/
  268. vAPI.messaging.setup = function(defaultHandler) {
  269. // Already setup?
  270. if ( this.defaultHandler !== null ) {
  271. return;
  272. }
  273. if ( typeof defaultHandler !== 'function' ) {
  274. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  275. }
  276. this.defaultHandler = defaultHandler;
  277. chrome.runtime.onConnect.addListener(this.onPortConnect);
  278. };
  279. /******************************************************************************/
  280. vAPI.messaging.broadcast = function(message) {
  281. var messageWrapper = {
  282. broadcast: true,
  283. msg: message
  284. };
  285. for ( var portName in this.ports ) {
  286. if ( this.ports.hasOwnProperty(portName) === false ) {
  287. continue;
  288. }
  289. this.ports[portName].postMessage(messageWrapper);
  290. }
  291. };
  292. /******************************************************************************/
  293. vAPI.net = {
  294. registerListeners: function() {
  295. var listeners = [
  296. 'onBeforeRequest',
  297. 'onBeforeSendHeaders',
  298. 'onHeadersReceived'
  299. ];
  300. for (var i = 0; i < listeners.length; ++i) {
  301. chrome.webRequest[listeners[i]].addListener(
  302. this[listeners[i]].callback,
  303. {
  304. 'urls': this[listeners[i]].urls || ['<all_urls>'],
  305. 'types': this[listeners[i]].types || []
  306. },
  307. this[listeners[i]].extra
  308. );
  309. }
  310. }
  311. };
  312. /******************************************************************************/
  313. vAPI.contextMenu = {
  314. create: function(details, callback) {
  315. this.menuId = details.id;
  316. this.callback = callback;
  317. chrome.contextMenus.create(details);
  318. chrome.contextMenus.onClicked.addListener(this.callback);
  319. },
  320. remove: function() {
  321. chrome.contextMenus.onClicked.removeListener(this.callback);
  322. chrome.contextMenus.remove(this.menuId);
  323. }
  324. };
  325. /******************************************************************************/
  326. vAPI.lastError = function() {
  327. return chrome.runtime.lastError;
  328. };
  329. /******************************************************************************/
  330. // This is called only once, when everything has been loaded in memory after
  331. // the extension was launched. It can be used to inject content scripts
  332. // in already opened web pages, to remove whatever nuisance could make it to
  333. // the web pages before uBlock was ready.
  334. vAPI.onLoadAllCompleted = function() {
  335. // http://code.google.com/p/chromium/issues/detail?id=410868#c11
  336. // Need to be sure to access `vAPI.lastError()` to prevent
  337. // spurious warnings in the console.
  338. var scriptDone = function() {
  339. vAPI.lastError();
  340. };
  341. var scriptEnd = function(tabId) {
  342. if ( vAPI.lastError() ) {
  343. return;
  344. }
  345. vAPI.tabs.injectScript(tabId, {
  346. file: 'js/contentscript-end.js',
  347. allFrames: true,
  348. runAt: 'document_idle'
  349. }, scriptDone);
  350. };
  351. var scriptStart = function(tabId) {
  352. vAPI.tabs.injectScript(tabId, {
  353. file: 'js/vapi-client.js',
  354. allFrames: true,
  355. runAt: 'document_start'
  356. }, function(){ });
  357. vAPI.tabs.injectScript(tabId, {
  358. file: 'js/contentscript-start.js',
  359. allFrames: true,
  360. runAt: 'document_start'
  361. }, function(){ scriptEnd(tabId); });
  362. };
  363. var bindToTabs = function(tabs) {
  364. var µb = µBlock;
  365. var i = tabs.length, tab;
  366. while ( i-- ) {
  367. tab = tabs[i];
  368. µb.bindTabToPageStats(tab.id, tab.url);
  369. // https://github.com/gorhill/uBlock/issues/129
  370. scriptStart(tab.id);
  371. }
  372. };
  373. chrome.tabs.query({ url: 'http://*/*' }, bindToTabs);
  374. chrome.tabs.query({ url: 'https://*/*' }, bindToTabs);
  375. };
  376. /******************************************************************************/
  377. })();
  378. /******************************************************************************/