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.

1414 lines
40 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
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
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
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
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
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
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
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
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
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
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
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 Services, XPCOMUtils, CustomizableUI */
  17. // For background page
  18. /******************************************************************************/
  19. (function() {
  20. 'use strict';
  21. /******************************************************************************/
  22. const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
  23. Cu['import']('resource://gre/modules/Services.jsm');
  24. Cu['import']('resource://gre/modules/XPCOMUtils.jsm');
  25. Cu['import']('resource:///modules/CustomizableUI.jsm');
  26. /******************************************************************************/
  27. self.vAPI = self.vAPI || {};
  28. vAPI.firefox = true;
  29. /******************************************************************************/
  30. // TODO: read these data from somewhere...
  31. vAPI.app = {
  32. name: 'µBlock',
  33. version: '0.8.2.3'
  34. };
  35. /******************************************************************************/
  36. vAPI.app.restart = function() {
  37. // Observing in bootstrap.js
  38. Services.obs.notifyObservers(null, location.host + '-restart', null);
  39. };
  40. /******************************************************************************/
  41. // List of things that needs to be destroyed when disabling the extension
  42. // Only functions should be added to it
  43. vAPI.unload = [];
  44. /******************************************************************************/
  45. var SQLite = {
  46. open: function() {
  47. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  48. path.append('extension-data');
  49. if ( !path.exists() ) {
  50. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  51. }
  52. if ( !path.isDirectory() ) {
  53. throw Error('Should be a directory...');
  54. }
  55. path.append(location.host + '.sqlite');
  56. this.db = Services.storage.openDatabase(path);
  57. this.db.executeSimpleSQL(
  58. 'CREATE TABLE IF NOT EXISTS settings' +
  59. '(name TEXT PRIMARY KEY NOT NULL, value TEXT);'
  60. );
  61. vAPI.unload.push(function() {
  62. // VACUUM somewhere else, instead on unload?
  63. SQLite.run('VACUUM');
  64. SQLite.db.asyncClose();
  65. });
  66. },
  67. run: function(query, values, callback) {
  68. if ( !this.db ) {
  69. this.open();
  70. }
  71. var result = {};
  72. query = this.db.createAsyncStatement(query);
  73. if ( Array.isArray(values) && values.length ) {
  74. var i = values.length;
  75. while ( i-- ) {
  76. query.bindByIndex(i, values[i]);
  77. }
  78. }
  79. query.executeAsync({
  80. handleResult: function(rows) {
  81. if ( !rows || typeof callback !== 'function' ) {
  82. return;
  83. }
  84. var row;
  85. while ( row = rows.getNextRow() ) {
  86. // we assume that there will be two columns, since we're
  87. // using it only for preferences
  88. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  89. }
  90. },
  91. handleCompletion: function(reason) {
  92. if ( typeof callback === 'function' && reason === 0 ) {
  93. callback(result);
  94. }
  95. },
  96. handleError: function(error) {
  97. console.error('SQLite error ', error.result, error.message);
  98. }
  99. });
  100. }
  101. };
  102. /******************************************************************************/
  103. vAPI.storage = {
  104. QUOTA_BYTES: 100 * 1024 * 1024,
  105. sqlWhere: function(col, params) {
  106. if ( params > 0 ) {
  107. params = Array(params + 1).join('?, ').slice(0, -2);
  108. return ' WHERE ' + col + ' IN (' + params + ')';
  109. }
  110. return '';
  111. },
  112. get: function(details, callback) {
  113. if ( typeof callback !== 'function' ) {
  114. return;
  115. }
  116. var values = [], defaults = false;
  117. if ( details !== null ) {
  118. if ( Array.isArray(details) ) {
  119. values = details;
  120. } else if ( typeof details === 'object' ) {
  121. defaults = true;
  122. values = Object.keys(details);
  123. } else {
  124. values = [details.toString()];
  125. }
  126. }
  127. SQLite.run(
  128. 'SELECT * FROM settings' + this.sqlWhere('name', values.length),
  129. values,
  130. function(result) {
  131. var key;
  132. for ( key in result ) {
  133. result[key] = JSON.parse(result[key]);
  134. }
  135. if ( defaults ) {
  136. for ( key in details ) {
  137. if ( result[key] === undefined ) {
  138. result[key] = details[key];
  139. }
  140. }
  141. }
  142. callback(result);
  143. }
  144. );
  145. },
  146. set: function(details, callback) {
  147. var key, values = [], placeholders = [];
  148. for ( key in details ) {
  149. values.push(key);
  150. values.push(JSON.stringify(details[key]));
  151. placeholders.push('?, ?');
  152. }
  153. if ( !values.length ) {
  154. return;
  155. }
  156. SQLite.run(
  157. 'INSERT OR REPLACE INTO settings (name, value) SELECT ' +
  158. placeholders.join(' UNION SELECT '),
  159. values,
  160. callback
  161. );
  162. },
  163. remove: function(keys, callback) {
  164. if ( typeof keys === 'string' ) {
  165. keys = [keys];
  166. }
  167. SQLite.run(
  168. 'DELETE FROM settings' + this.sqlWhere('name', keys.length),
  169. keys,
  170. callback
  171. );
  172. },
  173. clear: function(callback) {
  174. SQLite.run('DELETE FROM settings');
  175. SQLite.run('VACUUM', null, callback);
  176. },
  177. getBytesInUse: function(keys, callback) {
  178. if ( typeof callback !== 'function' ) {
  179. return;
  180. }
  181. SQLite.run(
  182. 'SELECT "size" AS size, SUM(LENGTH(value)) FROM settings' +
  183. this.sqlWhere('name', Array.isArray(keys) ? keys.length : 0),
  184. keys,
  185. function(result) {
  186. callback(result.size);
  187. }
  188. );
  189. }
  190. };
  191. /******************************************************************************/
  192. var windowWatcher = {
  193. onTabClose: function(e) {
  194. var tabId = vAPI.tabs.getTabId(e.target);
  195. vAPI.tabs.onClosed(tabId);
  196. delete vAPI.tabIcons[tabId];
  197. },
  198. onTabSelect: function(e) {
  199. vAPI.setIcon(
  200. vAPI.tabs.getTabId(e.target),
  201. e.target.ownerDocument.defaultView
  202. );
  203. },
  204. onReady: function(e) {
  205. if ( e ) {
  206. this.removeEventListener(e.type, windowWatcher.onReady);
  207. }
  208. var wintype = this.document.documentElement.getAttribute('windowtype');
  209. if ( wintype !== 'navigator:browser' ) {
  210. return;
  211. }
  212. if ( !this.gBrowser || !this.gBrowser.tabContainer ) {
  213. return;
  214. }
  215. var tC = this.gBrowser.tabContainer;
  216. this.gBrowser.addTabsProgressListener(tabsProgressListener);
  217. tC.addEventListener('TabClose', windowWatcher.onTabClose);
  218. tC.addEventListener('TabSelect', windowWatcher.onTabSelect);
  219. vAPI.toolbarButton.register(this.document);
  220. vAPI.contextMenu.register(this.document);
  221. // when new window is opened TabSelect doesn't run on the selected tab?
  222. },
  223. observe: function(win, topic) {
  224. if ( topic === 'domwindowopened' ) {
  225. win.addEventListener('DOMContentLoaded', this.onReady);
  226. }
  227. }
  228. };
  229. /******************************************************************************/
  230. var tabsProgressListener = {
  231. onLocationChange: function(browser, webProgress, request, location, flags) {
  232. if ( !webProgress.isTopLevel ) {
  233. return;
  234. }
  235. var tabId = vAPI.tabs.getTabId(browser);
  236. if ( flags & 1 ) {
  237. vAPI.tabs.onUpdated(tabId, {url: location.spec}, {
  238. frameId: 0,
  239. tabId: tabId,
  240. url: browser.currentURI.spec
  241. });
  242. } else if ( location.scheme === 'http' || location.scheme === 'https' ) {
  243. vAPI.tabs.onNavigation({
  244. frameId: 0,
  245. tabId: tabId,
  246. url: location.spec
  247. });
  248. }
  249. }
  250. };
  251. /******************************************************************************/
  252. vAPI.tabs = {};
  253. /******************************************************************************/
  254. vAPI.tabs.registerListeners = function() {
  255. // onNavigation and onUpdated handled with tabsProgressListener
  256. // onClosed - handled in windowWatcher.onTabClose
  257. // onPopup ?
  258. for ( var win of this.getWindows() ) {
  259. windowWatcher.onReady.call(win);
  260. }
  261. Services.ww.registerNotification(windowWatcher);
  262. vAPI.toolbarButton.init();
  263. vAPI.unload.push(function() {
  264. Services.ww.unregisterNotification(windowWatcher);
  265. for ( var win of vAPI.tabs.getWindows() ) {
  266. vAPI.toolbarButton.unregister(win.document);
  267. vAPI.contextMenu.unregister(win.document);
  268. win.removeEventListener('DOMContentLoaded', windowWatcher.onReady);
  269. win.gBrowser.removeTabsProgressListener(tabsProgressListener);
  270. var tC = win.gBrowser.tabContainer;
  271. tC.removeEventListener('TabClose', windowWatcher.onTabClose);
  272. tC.removeEventListener('TabSelect', windowWatcher.onTabSelect);
  273. // close extension tabs
  274. for ( var tab of win.gBrowser.tabs ) {
  275. var URI = tab.linkedBrowser.currentURI;
  276. if ( URI.scheme === 'chrome' && URI.host === location.host ) {
  277. win.gBrowser.removeTab(tab);
  278. }
  279. }
  280. }
  281. });
  282. };
  283. /******************************************************************************/
  284. vAPI.tabs.getTabId = function(target) {
  285. if ( target.linkedPanel ) {
  286. return target.linkedPanel.slice(6);
  287. }
  288. var i, gBrowser = target.ownerDocument.defaultView.gBrowser;
  289. // This should be more efficient from version 35
  290. if ( gBrowser.getTabForBrowser ) {
  291. i = gBrowser.getTabForBrowser(target);
  292. return i ? i.linkedPanel.slice(6) : -1;
  293. }
  294. i = gBrowser.browsers.indexOf(target);
  295. if ( i !== -1 ) {
  296. i = gBrowser.tabs[i].linkedPanel.slice(6);
  297. }
  298. return i;
  299. };
  300. /******************************************************************************/
  301. vAPI.tabs.get = function(tabId, callback) {
  302. var tab, windows;
  303. if ( tabId === null ) {
  304. tab = Services.wm.getMostRecentWindow('navigator:browser').gBrowser.selectedTab;
  305. tabId = vAPI.tabs.getTabId(tab);
  306. } else {
  307. windows = this.getWindows();
  308. for ( var win of windows ) {
  309. tab = win.gBrowser.tabContainer.querySelector(
  310. 'tab[linkedpanel="panel-' + tabId + '"]'
  311. );
  312. if ( tab ) {
  313. break;
  314. }
  315. }
  316. }
  317. // for internal use
  318. if ( tab && typeof callback !== 'function' ) {
  319. return tab;
  320. }
  321. if ( !tab ) {
  322. callback();
  323. return;
  324. }
  325. var browser = tab.linkedBrowser;
  326. var gBrowser = browser.ownerDocument.defaultView.gBrowser;
  327. if ( !windows ) {
  328. windows = this.getWindows();
  329. }
  330. callback({
  331. id: tabId,
  332. index: gBrowser.browsers.indexOf(browser),
  333. windowId: windows.indexOf(browser.ownerDocument.defaultView),
  334. active: tab === gBrowser.selectedTab,
  335. url: browser.currentURI.spec,
  336. title: tab.label
  337. });
  338. };
  339. /******************************************************************************/
  340. vAPI.tabs.getAll = function(window) {
  341. var win, tab, tabs = [];
  342. for ( win of this.getWindows() ) {
  343. if ( window && window !== win ) {
  344. continue;
  345. }
  346. for ( tab of win.gBrowser.tabs ) {
  347. tabs.push(tab);
  348. }
  349. }
  350. return tabs;
  351. };
  352. /******************************************************************************/
  353. vAPI.tabs.getWindows = function() {
  354. var winumerator = Services.wm.getEnumerator('navigator:browser');
  355. var windows = [];
  356. while ( winumerator.hasMoreElements() ) {
  357. var win = winumerator.getNext();
  358. if ( !win.closed ) {
  359. windows.push(win);
  360. }
  361. }
  362. return windows;
  363. };
  364. /******************************************************************************/
  365. // properties of the details object:
  366. // url: 'URL', // the address that will be opened
  367. // tabId: 1, // the tab is used if set, instead of creating a new one
  368. // index: -1, // undefined: end of the list, -1: following tab, or after index
  369. // active: false, // opens the tab in background - true and undefined: foreground
  370. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  371. vAPI.tabs.open = function(details) {
  372. if ( !details.url ) {
  373. return null;
  374. }
  375. // extension pages
  376. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  377. details.url = vAPI.getURL(details.url);
  378. }
  379. var tab, tabs;
  380. if ( details.select ) {
  381. var rgxHash = /#.*/;
  382. // this is questionable
  383. var url = details.url.replace(rgxHash, '');
  384. tabs = this.getAll();
  385. for ( tab of tabs ) {
  386. var browser = tab.linkedBrowser;
  387. if ( browser.currentURI.spec.replace(rgxHash, '') === url ) {
  388. browser.ownerDocument.defaultView.gBrowser.selectedTab = tab;
  389. return;
  390. }
  391. }
  392. }
  393. if ( details.active === undefined ) {
  394. details.active = true;
  395. }
  396. var gBrowser = Services.wm.getMostRecentWindow('navigator:browser').gBrowser;
  397. if ( details.index === -1 ) {
  398. details.index = gBrowser.browsers.indexOf(gBrowser.selectedBrowser) + 1;
  399. }
  400. if ( details.tabId ) {
  401. tabs = tabs || this.getAll();
  402. for ( tab of tabs ) {
  403. if ( vAPI.tabs.getTabId(tab) === details.tabId ) {
  404. tab.linkedBrowser.loadURI(details.url);
  405. return;
  406. }
  407. }
  408. }
  409. tab = gBrowser.loadOneTab(details.url, {inBackground: !details.active});
  410. if ( details.index !== undefined ) {
  411. gBrowser.moveTabTo(tab, details.index);
  412. }
  413. };
  414. /******************************************************************************/
  415. vAPI.tabs.remove = function(tabIds) {
  416. if ( !Array.isArray(tabIds) ) {
  417. tabIds = [tabIds];
  418. }
  419. tabIds = tabIds.map(function(tabId) {
  420. return 'tab[linkedpanel="panel-' + tabId + '"]';
  421. }).join(',');
  422. for ( var win of this.getWindows() ) {
  423. var tabs = win.gBrowser.tabContainer.querySelectorAll(tabIds);
  424. if ( !tabs ) {
  425. continue;
  426. }
  427. for ( var tab of tabs ) {
  428. win.gBrowser.removeTab(tab);
  429. }
  430. }
  431. };
  432. /******************************************************************************/
  433. vAPI.tabs.injectScript = function(tabId, details, callback) {
  434. var tab = vAPI.tabs.get(tabId);
  435. if ( !tab ) {
  436. return;
  437. }
  438. if ( details.file ) {
  439. details.file = vAPI.getURL(details.file);
  440. }
  441. tab.linkedBrowser.messageManager.sendAsyncMessage(
  442. location.host + ':broadcast',
  443. JSON.stringify({
  444. broadcast: true,
  445. channelName: 'vAPI',
  446. msg: {
  447. cmd: 'injectScript',
  448. details: details
  449. }
  450. })
  451. );
  452. if ( typeof callback === 'function' ) {
  453. setTimeout(callback, 13);
  454. }
  455. };
  456. /******************************************************************************/
  457. vAPI.tabIcons = { /*tabId: {badge: 0, img: boolean}*/ };
  458. vAPI.setIcon = function(tabId, iconStatus, badge) {
  459. // If badge is undefined, then setIcon was called from the TabSelect event
  460. var curWin = badge === undefined
  461. ? iconStatus
  462. : Services.wm.getMostRecentWindow('navigator:browser');
  463. var curTabId = vAPI.tabs.getTabId(curWin.gBrowser.selectedTab);
  464. // from 'TabSelect' event
  465. if ( tabId === undefined ) {
  466. tabId = curTabId;
  467. } else if ( badge !== undefined ) {
  468. vAPI.tabIcons[tabId] = {
  469. badge: badge,
  470. img: iconStatus === 'on'
  471. };
  472. }
  473. if ( tabId !== curTabId ) {
  474. return;
  475. }
  476. var button = curWin.document.getElementById(vAPI.toolbarButton.widgetId);
  477. if ( !button ) {
  478. return;
  479. }
  480. /*if ( !button.classList.contains('badged-button') ) {
  481. button.classList.add('badged-button');
  482. }*/
  483. var icon = vAPI.tabIcons[tabId];
  484. button.setAttribute('badge', icon && icon.badge || '');
  485. iconStatus = !button.image || !icon || !icon.img ? '-off' : '';
  486. button.image = vAPI.getURL('img/browsericons/icon16' + iconStatus + '.svg');
  487. };
  488. /******************************************************************************/
  489. vAPI.toolbarButton = {
  490. widgetId: location.host + '-button',
  491. panelId: location.host + '-panel'
  492. };
  493. /******************************************************************************/
  494. vAPI.toolbarButton.init = function() {
  495. CustomizableUI.createWidget({
  496. id: this.widgetId,
  497. type: 'view',
  498. viewId: this.panelId,
  499. defaultArea: CustomizableUI.AREA_NAVBAR,
  500. label: vAPI.app.name,
  501. tooltiptext: vAPI.app.name,
  502. onViewShowing: function({target}) {
  503. var hash = CustomizableUI.getWidget(vAPI.toolbarButton.widgetId)
  504. .areaType === CustomizableUI.TYPE_TOOLBAR ? '' : '#body';
  505. target.firstChild.setAttribute(
  506. 'src',
  507. vAPI.getURL('popup.html' + hash)
  508. );
  509. },
  510. onViewHiding: function({target}) {
  511. target.firstChild.setAttribute('src', 'about:blank');
  512. }
  513. });
  514. this.closePopup = function({target}) {
  515. CustomizableUI.hidePanelForNode(
  516. target.ownerDocument.getElementById(vAPI.toolbarButton.panelId)
  517. );
  518. };
  519. vAPI.messaging.globalMessageManager.addMessageListener(
  520. location.host + ':closePopup',
  521. this.closePopup
  522. );
  523. vAPI.unload.push(function() {
  524. CustomizableUI.destroyWidget(vAPI.toolbarButton.widgetId);
  525. vAPI.messaging.globalMessageManager.removeMessageListener(
  526. location.host + ':closePopup',
  527. vAPI.toolbarButton.closePopup
  528. );
  529. });
  530. };
  531. /******************************************************************************/
  532. // it runs with windowWatcher when a window is opened
  533. // vAPI.tabs.registerListeners initializes it
  534. vAPI.toolbarButton.register = function(doc) {
  535. var panel = doc.createElement('panelview');
  536. panel.setAttribute('id', this.panelId);
  537. var iframe = doc.createElement('iframe');
  538. iframe.setAttribute('type', 'content');
  539. doc.getElementById('PanelUI-multiView')
  540. .appendChild(panel)
  541. .appendChild(iframe);
  542. var updateTimer = null;
  543. var delayedResize = function() {
  544. if ( updateTimer ) {
  545. return;
  546. }
  547. updateTimer = setTimeout(resizePopup, 20);
  548. };
  549. var resizePopup = function() {
  550. var panelStyle = panel.style;
  551. var body = iframe.contentDocument.body;
  552. panelStyle.width = iframe.style.width = body.clientWidth + 'px';
  553. panelStyle.height = iframe.style.height = body.clientHeight + 'px';
  554. updateTimer = null;
  555. };
  556. var onPopupReady = function() {
  557. var win = this.contentWindow;
  558. if ( !win || win.location.host !== location.host ) {
  559. return;
  560. }
  561. new win.MutationObserver(delayedResize).observe(win.document, {
  562. childList: true,
  563. attributes: true,
  564. characterData: true,
  565. subtree: true
  566. });
  567. delayedResize();
  568. };
  569. iframe.addEventListener('load', onPopupReady, true);
  570. if ( !this.styleURI ) {
  571. this.styleURI = 'data:text/css,' + encodeURIComponent([
  572. '#' + this.widgetId + ' {',
  573. 'list-style-image: url(',
  574. vAPI.getURL('img/browsericons/icon16-off.svg'),
  575. ');',
  576. '}',
  577. '#' + this.widgetId + '[badge]:not([badge=""])::after {',
  578. 'position: absolute;',
  579. 'margin-left: -16px;',
  580. 'margin-top: 3px;',
  581. 'padding: 1px 2px;',
  582. 'font-size: 9px;',
  583. 'font-weight: bold;',
  584. 'color: #fff;',
  585. 'background: #666;',
  586. 'content: attr(badge);',
  587. '}',
  588. '#' + this.panelId + ', #' + this.panelId + ' > iframe {',
  589. 'width: 180px;',
  590. 'height: 310px;',
  591. 'overflow: hidden !important;',
  592. '}'
  593. ].join(''));
  594. this.styleURI = Services.io.newURI(this.styleURI, null, null);
  595. }
  596. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  597. getInterface(Ci.nsIDOMWindowUtils).loadSheet(this.styleURI, 1);
  598. };
  599. /******************************************************************************/
  600. vAPI.toolbarButton.unregister = function(doc) {
  601. var panel = doc.getElementById(this.panelId);
  602. panel.parentNode.removeChild(panel);
  603. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  604. getInterface(Ci.nsIDOMWindowUtils).removeSheet(this.styleURI, 1);
  605. };
  606. /******************************************************************************/
  607. vAPI.messaging = {
  608. get globalMessageManager() {
  609. return Cc['@mozilla.org/globalmessagemanager;1']
  610. .getService(Ci.nsIMessageListenerManager);
  611. },
  612. frameScript: vAPI.getURL('frameScript.js'),
  613. listeners: {},
  614. defaultHandler: null,
  615. NOOPFUNC: function(){},
  616. UNHANDLED: 'vAPI.messaging.notHandled'
  617. };
  618. /******************************************************************************/
  619. vAPI.messaging.listen = function(listenerName, callback) {
  620. this.listeners[listenerName] = callback;
  621. };
  622. /******************************************************************************/
  623. vAPI.messaging.onMessage = function({target, data}) {
  624. var messageManager = target.messageManager;
  625. if ( !messageManager ) {
  626. // Message came from a popup, and its message manager is not usable.
  627. // So instead we broadcast to the parent window.
  628. messageManager = target
  629. .webNavigation.QueryInterface(Ci.nsIDocShell)
  630. .chromeEventHandler.ownerDocument.defaultView.messageManager;
  631. }
  632. var listenerId = data.channelName.split('|');
  633. var requestId = data.requestId;
  634. var channelName = listenerId[1];
  635. listenerId = listenerId[0];
  636. var callback = vAPI.messaging.NOOPFUNC;
  637. if ( requestId !== undefined ) {
  638. callback = function(response) {
  639. var message = JSON.stringify({
  640. requestId: requestId,
  641. channelName: channelName,
  642. msg: response !== undefined ? response : null
  643. });
  644. if ( messageManager.sendAsyncMessage ) {
  645. messageManager.sendAsyncMessage(listenerId, message);
  646. } else {
  647. messageManager.broadcastAsyncMessage(listenerId, message);
  648. }
  649. };
  650. }
  651. var sender = {
  652. tab: {
  653. id: vAPI.tabs.getTabId(target)
  654. }
  655. };
  656. // Specific handler
  657. var r = vAPI.messaging.UNHANDLED;
  658. var listener = vAPI.messaging.listeners[channelName];
  659. if ( typeof listener === 'function' ) {
  660. r = listener(data.msg, sender, callback);
  661. }
  662. if ( r !== vAPI.messaging.UNHANDLED ) {
  663. return;
  664. }
  665. // Default handler
  666. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  667. if ( r !== vAPI.messaging.UNHANDLED ) {
  668. return;
  669. }
  670. console.error('µBlock> messaging > unknown request: %o', data);
  671. // Unhandled:
  672. // Need to callback anyways in case caller expected an answer, or
  673. // else there is a memory leak on caller's side
  674. callback();
  675. };
  676. /******************************************************************************/
  677. vAPI.messaging.setup = function(defaultHandler) {
  678. // Already setup?
  679. if ( this.defaultHandler !== null ) {
  680. return;
  681. }
  682. if ( typeof defaultHandler !== 'function' ) {
  683. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  684. }
  685. this.defaultHandler = defaultHandler;
  686. this.globalMessageManager.addMessageListener(
  687. location.host + ':background',
  688. this.onMessage
  689. );
  690. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  691. vAPI.unload.push(function() {
  692. var gmm = vAPI.messaging.globalMessageManager;
  693. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  694. gmm.removeMessageListener(
  695. location.host + ':background',
  696. vAPI.messaging.onMessage
  697. );
  698. });
  699. };
  700. /******************************************************************************/
  701. vAPI.messaging.broadcast = function(message) {
  702. this.globalMessageManager.broadcastAsyncMessage(
  703. location.host + ':broadcast',
  704. JSON.stringify({broadcast: true, msg: message})
  705. );
  706. };
  707. /******************************************************************************/
  708. var httpObserver = {
  709. classDescription: 'net-channel-event-sinks for ' + location.host,
  710. classID: Components.ID('{dc8d6319-5f6e-4438-999e-53722db99e84}'),
  711. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  712. ABORT: Components.results.NS_BINDING_ABORTED,
  713. ACCEPT: Components.results.NS_SUCCEEDED,
  714. MAIN_FRAME: Ci.nsIContentPolicy.TYPE_DOCUMENT,
  715. typeMap: {
  716. 2: 'script',
  717. 3: 'image',
  718. 4: 'stylesheet',
  719. 5: 'object',
  720. 6: 'main_frame',
  721. 7: 'sub_frame',
  722. 11: 'xmlhttprequest'
  723. },
  724. lastRequest: {
  725. url: null,
  726. type: null,
  727. tabId: null,
  728. frameId: null,
  729. parentFrameId: null,
  730. opener: null
  731. },
  732. get componentRegistrar() {
  733. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  734. },
  735. get categoryManager() {
  736. return Cc['@mozilla.org/categorymanager;1']
  737. .getService(Ci.nsICategoryManager);
  738. },
  739. QueryInterface: XPCOMUtils.generateQI([
  740. Ci.nsIFactory,
  741. Ci.nsIObserver,
  742. Ci.nsIChannelEventSink,
  743. Ci.nsISupportsWeakReference
  744. ]),
  745. createInstance: function(outer, iid) {
  746. if ( outer ) {
  747. throw Components.results.NS_ERROR_NO_AGGREGATION;
  748. }
  749. return this.QueryInterface(iid);
  750. },
  751. register: function() {
  752. Services.obs.addObserver(this, 'http-on-opening-request', true);
  753. Services.obs.addObserver(this, 'http-on-examine-response', true);
  754. this.componentRegistrar.registerFactory(
  755. this.classID,
  756. this.classDescription,
  757. this.contractID,
  758. this
  759. );
  760. this.categoryManager.addCategoryEntry(
  761. 'net-channel-event-sinks',
  762. this.contractID,
  763. this.contractID,
  764. false,
  765. true
  766. );
  767. },
  768. unregister: function() {
  769. Services.obs.removeObserver(this, 'http-on-opening-request');
  770. Services.obs.removeObserver(this, 'http-on-examine-response');
  771. this.componentRegistrar.unregisterFactory(this.classID, this);
  772. this.categoryManager.deleteCategoryEntry(
  773. 'net-channel-event-sinks',
  774. this.contractID,
  775. false
  776. );
  777. },
  778. handlePopup: function(URI, tabId, sourceTabId) {
  779. if ( !sourceTabId ) {
  780. return false;
  781. }
  782. if ( URI.scheme !== 'http' && URI.scheme !== 'https' ) {
  783. return false;
  784. }
  785. var result = vAPI.tabs.onPopup({
  786. tabId: tabId,
  787. sourceTabId: sourceTabId,
  788. url: URI.spec
  789. });
  790. return result === true;
  791. },
  792. handleRequest: function(channel, details) {
  793. var onBeforeRequest = vAPI.net.onBeforeRequest;
  794. var type = this.typeMap[details.type] || 'other';
  795. if ( onBeforeRequest.types.has(type) === false ) {
  796. return false;
  797. }
  798. var result = onBeforeRequest.callback({
  799. url: channel.URI.spec,
  800. type: type,
  801. tabId: details.tabId,
  802. frameId: details.frameId,
  803. parentFrameId: details.parentFrameId
  804. });
  805. if ( !result || typeof result !== 'object' ) {
  806. return false;
  807. }
  808. if ( result.cancel === true ) {
  809. channel.cancel(this.ABORT);
  810. return true;
  811. } else if ( result.redirectUrl ) {
  812. channel.redirectionLimit = 1;
  813. channel.redirectTo(
  814. Services.io.newURI(result.redirectUrl, null, null)
  815. );
  816. return true;
  817. }
  818. return false;
  819. },
  820. observe: function(channel, topic) {
  821. if ( !(channel instanceof Ci.nsIHttpChannel) ) {
  822. return;
  823. }
  824. var URI = channel.URI;
  825. var channelData, result;
  826. if ( topic === 'http-on-examine-response' ) {
  827. if ( !(channel instanceof Ci.nsIWritablePropertyBag) ) {
  828. return;
  829. }
  830. try {
  831. channelData = channel.getProperty(location.host + 'reqdata');
  832. } catch (ex) {
  833. return;
  834. }
  835. // [tabId, type, sourceTabId - given if it was a popup]
  836. if ( !channelData || channelData[0] !== this.MAIN_FRAME ) {
  837. return;
  838. }
  839. topic = 'Content-Security-Policy';
  840. try {
  841. result = channel.getResponseHeader(topic);
  842. } catch (ex) {
  843. result = null;
  844. }
  845. result = vAPI.net.onHeadersReceived.callback({
  846. url: URI.spec,
  847. tabId: channelData[1],
  848. parentFrameId: -1,
  849. responseHeaders: result ? [{name: topic, value: result}] : []
  850. });
  851. if ( result ) {
  852. channel.setResponseHeader(
  853. topic,
  854. result.responseHeaders.pop().value,
  855. true
  856. );
  857. }
  858. return;
  859. }
  860. // http-on-opening-request
  861. var lastRequest = this.lastRequest;
  862. if ( !lastRequest.url || lastRequest.url !== URI.spec ) {
  863. lastRequest.url = null;
  864. return;
  865. }
  866. // Important! When loading file via XHR for mirroring,
  867. // the URL will be the same, so it could fall into an infinite loop
  868. lastRequest.url = null;
  869. var sourceTabId = null;
  870. // popup candidate (only for main_frame type)
  871. if ( lastRequest.opener ) {
  872. for ( var tab of vAPI.tabs.getAll() ) {
  873. var tabURI = tab.linkedBrowser.currentURI;
  874. // not the best approach
  875. if ( tabURI.spec === this.lastRequest.opener ) {
  876. sourceTabId = vAPI.tabs.getTabId(tab);
  877. break;
  878. }
  879. }
  880. if ( this.handlePopup(channel.URI, lastRequest.tabId, sourceTabId) ) {
  881. channel.cancel(this.ABORT);
  882. return;
  883. }
  884. }
  885. if ( this.handleRequest(channel, lastRequest) ) {
  886. return;
  887. }
  888. // if request is not handled we may use the data in on-modify-request
  889. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  890. channel.setProperty(
  891. location.host + 'reqdata',
  892. [lastRequest.type, lastRequest.tabId, sourceTabId]
  893. );
  894. }
  895. },
  896. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  897. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  898. var result = this.ACCEPT;
  899. // If error thrown, the redirect will fail
  900. try {
  901. // skip internal redirects?
  902. /*if ( flags & 4 ) {
  903. console.log('internal redirect skipped');
  904. return;
  905. }*/
  906. var scheme = newChannel.URI.scheme;
  907. if ( scheme !== 'http' && scheme !== 'https' ) {
  908. return;
  909. }
  910. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  911. return;
  912. }
  913. var channelData = oldChannel.getProperty(location.host + 'reqdata');
  914. var [type, tabId, sourceTabId] = channelData;
  915. if ( this.handlePopup(newChannel.URI, tabId, sourceTabId) ) {
  916. result = this.ABORT;
  917. return;
  918. }
  919. var details = {
  920. type: type,
  921. tabId: tabId,
  922. // well...
  923. frameId: type === this.MAIN_FRAME ? -1 : 0,
  924. parentFrameId: -1
  925. };
  926. if ( this.handleRequest(newChannel, details) ) {
  927. result = this.ABORT;
  928. return;
  929. }
  930. // carry the data on in case of multiple redirects
  931. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  932. newChannel.setProperty(location.host + 'reqdata', channelData);
  933. }
  934. } catch (ex) {
  935. // console.error(ex);
  936. } finally {
  937. callback.onRedirectVerifyCallback(result);
  938. }
  939. }
  940. };
  941. /******************************************************************************/
  942. vAPI.net = {};
  943. /******************************************************************************/
  944. vAPI.net.registerListeners = function() {
  945. this.onBeforeRequest.types = new Set(this.onBeforeRequest.types);
  946. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  947. var shouldLoadListener = function(e) {
  948. var details = e.data;
  949. // data: and about:blank
  950. if ( details.url.charAt(0) !== 'h' ) {
  951. vAPI.net.onBeforeRequest.callback({
  952. url: 'http://' + details.url.slice(0, details.url.indexOf(':')),
  953. type: 'main_frame',
  954. tabId: vAPI.tabs.getTabId(e.target),
  955. frameId: details.frameId,
  956. parentFrameId: details.parentFrameId
  957. });
  958. return;
  959. }
  960. var lastRequest = httpObserver.lastRequest;
  961. lastRequest.url = details.url;
  962. lastRequest.type = details.type;
  963. lastRequest.tabId = vAPI.tabs.getTabId(e.target);
  964. lastRequest.frameId = details.frameId;
  965. lastRequest.parentFrameId = details.parentFrameId;
  966. lastRequest.opener = details.opener;
  967. };
  968. vAPI.messaging.globalMessageManager.addMessageListener(
  969. shouldLoadListenerMessageName,
  970. shouldLoadListener
  971. );
  972. httpObserver.register();
  973. vAPI.unload.push(function() {
  974. vAPI.messaging.globalMessageManager.removeMessageListener(
  975. shouldLoadListenerMessageName,
  976. shouldLoadListener
  977. );
  978. httpObserver.unregister();
  979. });
  980. };
  981. /******************************************************************************/
  982. vAPI.contextMenu = {
  983. contextMap: {
  984. frame: 'inFrame',
  985. link: 'onLink',
  986. image: 'onImage',
  987. audio: 'onAudio',
  988. video: 'onVideo',
  989. editable: 'onEditableArea'
  990. }
  991. };
  992. /******************************************************************************/
  993. vAPI.contextMenu.displayMenuItem = function(e) {
  994. var doc = e.target.ownerDocument;
  995. var gContextMenu = doc.defaultView.gContextMenu;
  996. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  997. if ( /^https?$/.test(gContextMenu.browser.currentURI.scheme) === false) {
  998. menuitem.hidden = true;
  999. return;
  1000. }
  1001. var ctx = vAPI.contextMenu.contexts;
  1002. if ( !ctx ) {
  1003. menuitem.hidden = false;
  1004. return;
  1005. }
  1006. var ctxMap = vAPI.contextMenu.contextMap;
  1007. for ( var context of ctx ) {
  1008. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  1009. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  1010. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  1011. menuitem.hidden = false;
  1012. return;
  1013. }
  1014. if ( gContextMenu[ctxMap[context]] ) {
  1015. menuitem.hidden = false;
  1016. return;
  1017. }
  1018. }
  1019. menuitem.hidden = true;
  1020. };
  1021. /******************************************************************************/
  1022. vAPI.contextMenu.register = function(doc) {
  1023. if ( !this.menuItemId ) {
  1024. return;
  1025. }
  1026. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1027. var menuitem = doc.createElement('menuitem');
  1028. menuitem.setAttribute('id', this.menuItemId);
  1029. menuitem.setAttribute('label', this.menuLabel);
  1030. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  1031. menuitem.setAttribute('class', 'menuitem-iconic');
  1032. menuitem.addEventListener('command', this.onCommand);
  1033. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1034. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1035. };
  1036. /******************************************************************************/
  1037. vAPI.contextMenu.unregister = function(doc) {
  1038. if ( !this.menuItemId ) {
  1039. return;
  1040. }
  1041. var menuitem = doc.getElementById(this.menuItemId);
  1042. var contextMenu = menuitem.parentNode;
  1043. menuitem.removeEventListener('command', this.onCommand);
  1044. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1045. contextMenu.removeChild(menuitem);
  1046. };
  1047. /******************************************************************************/
  1048. vAPI.contextMenu.create = function(details, callback) {
  1049. this.menuItemId = details.id;
  1050. this.menuLabel = details.title;
  1051. this.contexts = details.contexts;
  1052. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1053. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1054. } else {
  1055. // default in Chrome
  1056. this.contexts = ['page'];
  1057. }
  1058. this.onCommand = function() {
  1059. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  1060. var details = {
  1061. menuItemId: this.id,
  1062. tagName: gContextMenu.target.tagName.toLowerCase()
  1063. };
  1064. if ( gContextMenu.inFrame ) {
  1065. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1066. } else if ( gContextMenu.onImage || gContextMenu.onAudio || gContextMenu.onVideo ) {
  1067. details.srcUrl = gContextMenu.mediaURL;
  1068. } else if ( gContextMenu.onLink ) {
  1069. details.linkUrl = gContextMenu.linkURL;
  1070. }
  1071. callback(details, {
  1072. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1073. url: gContextMenu.browser.currentURI.spec
  1074. });
  1075. };
  1076. for ( var win of vAPI.tabs.getWindows() ) {
  1077. this.register(win.document);
  1078. }
  1079. };
  1080. /******************************************************************************/
  1081. vAPI.contextMenu.remove = function() {
  1082. for ( var win of vAPI.tabs.getWindows() ) {
  1083. this.unregister(win.document);
  1084. }
  1085. this.menuItemId = null;
  1086. this.menuLabel = null;
  1087. this.contexts = null;
  1088. this.onCommand = null;
  1089. };
  1090. /******************************************************************************/
  1091. vAPI.lastError = function() {
  1092. return null;
  1093. };
  1094. /******************************************************************************/
  1095. // This is called only once, when everything has been loaded in memory after
  1096. // the extension was launched. It can be used to inject content scripts
  1097. // in already opened web pages, to remove whatever nuisance could make it to
  1098. // the web pages before uBlock was ready.
  1099. vAPI.onLoadAllCompleted = function() {};
  1100. /******************************************************************************/
  1101. // clean up when the extension is disabled
  1102. window.addEventListener('unload', function() {
  1103. for ( var unload of vAPI.unload ) {
  1104. unload();
  1105. }
  1106. // frameModule needs to be cleared too
  1107. var frameModule = {};
  1108. Cu['import'](vAPI.getURL('frameModule.js'), frameModule);
  1109. frameModule.contentObserver.unregister();
  1110. Cu.unload(vAPI.getURL('frameModule.js'));
  1111. });
  1112. /******************************************************************************/
  1113. })();
  1114. /******************************************************************************/