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.

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