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.

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