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.

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