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.

1981 lines
58 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
  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/uMatrix
  15. */
  16. /* jshint bitwise: false, boss: true, esnext: true */
  17. /* global self, Components, punycode, µBlock */
  18. // For background page
  19. /******************************************************************************/
  20. (function() {
  21. 'use strict';
  22. /******************************************************************************/
  23. // Useful links
  24. //
  25. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface
  26. /******************************************************************************/
  27. const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
  28. const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
  29. /******************************************************************************/
  30. var vAPI = self.vAPI = self.vAPI || {};
  31. vAPI.firefox = true;
  32. /******************************************************************************/
  33. vAPI.app = {
  34. name: 'uMatrix',
  35. version: location.hash.slice(1)
  36. };
  37. /******************************************************************************/
  38. vAPI.app.start = function() {
  39. };
  40. /******************************************************************************/
  41. vAPI.app.stop = function() {
  42. };
  43. /******************************************************************************/
  44. vAPI.app.restart = function() {
  45. // Listening in bootstrap.js
  46. Cc['@mozilla.org/childprocessmessagemanager;1']
  47. .getService(Ci.nsIMessageSender)
  48. .sendAsyncMessage(location.host + '-restart');
  49. };
  50. /******************************************************************************/
  51. // List of things that needs to be destroyed when disabling the extension
  52. // Only functions should be added to it
  53. var cleanupTasks = [];
  54. // This must be updated manually, every time a new task is added/removed
  55. // Fixed by github.com/AlexVallat:
  56. // https://github.com/AlexVallat/uBlock/commit/7b781248f00cbe3d61b1cc367c440db80fa06049
  57. // 7 instances of cleanupTasks.push, but one is unique to fennec, and one to desktop.
  58. var expectedNumberOfCleanups = 6;
  59. window.addEventListener('unload', function() {
  60. for ( var cleanup of cleanupTasks ) {
  61. cleanup();
  62. }
  63. if ( cleanupTasks.length < expectedNumberOfCleanups ) {
  64. console.error(
  65. 'uMatrix> Cleanup tasks performed: %s (out of %s)',
  66. cleanupTasks.length,
  67. expectedNumberOfCleanups
  68. );
  69. }
  70. // frameModule needs to be cleared too
  71. var frameModule = {};
  72. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  73. frameModule.contentObserver.unregister();
  74. Cu.unload(vAPI.getURL('frameModule.js'));
  75. });
  76. /******************************************************************************/
  77. var SQLite = {
  78. open: function() {
  79. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  80. path.append('extension-data');
  81. if ( !path.exists() ) {
  82. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  83. }
  84. if ( !path.isDirectory() ) {
  85. throw Error('Should be a directory...');
  86. }
  87. path.append(location.host + '.sqlite');
  88. this.db = Services.storage.openDatabase(path);
  89. this.db.executeSimpleSQL(
  90. 'CREATE TABLE IF NOT EXISTS settings' +
  91. '(name TEXT PRIMARY KEY NOT NULL, value TEXT);'
  92. );
  93. cleanupTasks.push(function() {
  94. // VACUUM somewhere else, instead on unload?
  95. SQLite.run('VACUUM');
  96. SQLite.db.asyncClose();
  97. });
  98. },
  99. run: function(query, values, callback) {
  100. if ( !this.db ) {
  101. this.open();
  102. }
  103. var result = {};
  104. query = this.db.createAsyncStatement(query);
  105. if ( Array.isArray(values) && values.length ) {
  106. var i = values.length;
  107. while ( i-- ) {
  108. query.bindByIndex(i, values[i]);
  109. }
  110. }
  111. query.executeAsync({
  112. handleResult: function(rows) {
  113. if ( !rows || typeof callback !== 'function' ) {
  114. return;
  115. }
  116. var row;
  117. while ( row = rows.getNextRow() ) {
  118. // we assume that there will be two columns, since we're
  119. // using it only for preferences
  120. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  121. }
  122. },
  123. handleCompletion: function(reason) {
  124. if ( typeof callback === 'function' && reason === 0 ) {
  125. callback(result);
  126. }
  127. },
  128. handleError: function(error) {
  129. console.error('SQLite error ', error.result, error.message);
  130. }
  131. });
  132. }
  133. };
  134. /******************************************************************************/
  135. vAPI.storage = {
  136. QUOTA_BYTES: 100 * 1024 * 1024,
  137. sqlWhere: function(col, params) {
  138. if ( params > 0 ) {
  139. params = new Array(params + 1).join('?, ').slice(0, -2);
  140. return ' WHERE ' + col + ' IN (' + params + ')';
  141. }
  142. return '';
  143. },
  144. get: function(details, callback) {
  145. if ( typeof callback !== 'function' ) {
  146. return;
  147. }
  148. var values = [], defaults = false;
  149. if ( details !== null ) {
  150. if ( Array.isArray(details) ) {
  151. values = details;
  152. } else if ( typeof details === 'object' ) {
  153. defaults = true;
  154. values = Object.keys(details);
  155. } else {
  156. values = [details.toString()];
  157. }
  158. }
  159. SQLite.run(
  160. 'SELECT * FROM settings' + this.sqlWhere('name', values.length),
  161. values,
  162. function(result) {
  163. var key;
  164. for ( key in result ) {
  165. result[key] = JSON.parse(result[key]);
  166. }
  167. if ( defaults ) {
  168. for ( key in details ) {
  169. if ( result[key] === undefined ) {
  170. result[key] = details[key];
  171. }
  172. }
  173. }
  174. callback(result);
  175. }
  176. );
  177. },
  178. set: function(details, callback) {
  179. var key, values = [], placeholders = [];
  180. for ( key in details ) {
  181. if ( !details.hasOwnProperty(key) ) {
  182. continue;
  183. }
  184. values.push(key);
  185. values.push(JSON.stringify(details[key]));
  186. placeholders.push('?, ?');
  187. }
  188. if ( !values.length ) {
  189. return;
  190. }
  191. SQLite.run(
  192. 'INSERT OR REPLACE INTO settings (name, value) SELECT ' +
  193. placeholders.join(' UNION SELECT '),
  194. values,
  195. callback
  196. );
  197. },
  198. remove: function(keys, callback) {
  199. if ( typeof keys === 'string' ) {
  200. keys = [keys];
  201. }
  202. SQLite.run(
  203. 'DELETE FROM settings' + this.sqlWhere('name', keys.length),
  204. keys,
  205. callback
  206. );
  207. },
  208. clear: function(callback) {
  209. SQLite.run('DELETE FROM settings');
  210. SQLite.run('VACUUM', null, callback);
  211. },
  212. getBytesInUse: function(keys, callback) {
  213. if ( typeof callback !== 'function' ) {
  214. return;
  215. }
  216. SQLite.run(
  217. 'SELECT "size" AS size, SUM(LENGTH(value)) FROM settings' +
  218. this.sqlWhere('name', Array.isArray(keys) ? keys.length : 0),
  219. keys,
  220. function(result) {
  221. callback(result.size);
  222. }
  223. );
  224. }
  225. };
  226. /******************************************************************************/
  227. var windowWatcher = {
  228. onReady: function(e) {
  229. if ( e ) {
  230. this.removeEventListener(e.type, windowWatcher.onReady);
  231. }
  232. var wintype = this.document.documentElement.getAttribute('windowtype');
  233. if ( wintype !== 'navigator:browser' ) {
  234. return;
  235. }
  236. var tabContainer;
  237. var tabBrowser = getTabBrowser(this);
  238. if ( !tabBrowser ) {
  239. return;
  240. }
  241. if ( tabBrowser.tabContainer ) {
  242. // desktop Firefox
  243. tabContainer = tabBrowser.tabContainer;
  244. vAPI.contextMenu.register(this.document);
  245. } else {
  246. return;
  247. }
  248. tabContainer.addEventListener('TabClose', tabWatcher.onTabClose);
  249. tabContainer.addEventListener('TabSelect', tabWatcher.onTabSelect);
  250. // when new window is opened TabSelect doesn't run on the selected tab?
  251. },
  252. observe: function(win, topic) {
  253. if ( topic === 'domwindowopened' ) {
  254. win.addEventListener('DOMContentLoaded', this.onReady);
  255. }
  256. }
  257. };
  258. /******************************************************************************/
  259. var tabWatcher = {
  260. onTabClose: function({target}) {
  261. // target is tab in Firefox, browser in Fennec
  262. var tabId = vAPI.tabs.getTabId(target);
  263. vAPI.tabs.onClosed(tabId);
  264. delete vAPI.toolbarButton.tabs[tabId];
  265. },
  266. onTabSelect: function({target}) {
  267. vAPI.setIcon(vAPI.tabs.getTabId(target), getOwnerWindow(target));
  268. return;
  269. },
  270. };
  271. /******************************************************************************/
  272. vAPI.isBehindTheSceneTabId = function(tabId) {
  273. return tabId.toString() === '-1';
  274. };
  275. vAPI.noTabId = '-1';
  276. /******************************************************************************/
  277. var getTabBrowser = function(win) {
  278. return win.gBrowser || null;
  279. };
  280. /******************************************************************************/
  281. var getBrowserForTab = function(tab) {
  282. if ( !tab ) {
  283. return null;
  284. }
  285. return tab.linkedBrowser || null;
  286. };
  287. /******************************************************************************/
  288. var getOwnerWindow = function(target) {
  289. if ( target.ownerDocument ) {
  290. return target.ownerDocument.defaultView;
  291. }
  292. return null;
  293. };
  294. /******************************************************************************/
  295. vAPI.tabs = {};
  296. /******************************************************************************/
  297. vAPI.tabs.registerListeners = function() {
  298. // onClosed - handled in tabWatcher.onTabClose
  299. // onPopup - handled in httpObserver.handlePopup
  300. for ( var win of this.getWindows() ) {
  301. windowWatcher.onReady.call(win);
  302. }
  303. Services.ww.registerNotification(windowWatcher);
  304. cleanupTasks.push(function() {
  305. Services.ww.unregisterNotification(windowWatcher);
  306. for ( var win of vAPI.tabs.getWindows() ) {
  307. vAPI.contextMenu.unregister(win.document);
  308. win.removeEventListener('DOMContentLoaded', windowWatcher.onReady);
  309. var tabContainer;
  310. var tabBrowser = getTabBrowser(win);
  311. if ( !tabBrowser ) {
  312. continue;
  313. }
  314. if ( tabBrowser.tabContainer ) {
  315. tabContainer = tabBrowser.tabContainer;
  316. tabBrowser.removeTabsProgressListener(tabWatcher);
  317. }
  318. tabContainer.removeEventListener('TabClose', tabWatcher.onTabClose);
  319. tabContainer.removeEventListener('TabSelect', tabWatcher.onTabSelect);
  320. // Close extension tabs
  321. for ( var tab of tabBrowser.tabs ) {
  322. var browser = getBrowserForTab(tab);
  323. if ( browser === null ) {
  324. continue;
  325. }
  326. var URI = browser.currentURI;
  327. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  328. vAPI.tabs._remove(tab, getTabBrowser(win));
  329. }
  330. }
  331. }
  332. });
  333. };
  334. /******************************************************************************/
  335. vAPI.tabs.stack = new WeakMap();
  336. vAPI.tabs.stackId = 1;
  337. /******************************************************************************/
  338. vAPI.tabs.getTabId = function(target) {
  339. if ( !target ) {
  340. return vAPI.noTabId;
  341. }
  342. if ( target.linkedPanel ) {
  343. // target is a tab
  344. target = target.linkedBrowser;
  345. }
  346. if ( target.localName !== 'browser' ) {
  347. return vAPI.noTabId;
  348. }
  349. var tabId = this.stack.get(target);
  350. if ( !tabId ) {
  351. tabId = '' + this.stackId++;
  352. this.stack.set(target, tabId);
  353. }
  354. return tabId;
  355. };
  356. /******************************************************************************/
  357. // If tabIds is an array, then an array of tabs will be returned,
  358. // otherwise a single tab
  359. vAPI.tabs.getTabsForIds = function(tabIds) {
  360. var tabs = [];
  361. var singleTab = !Array.isArray(tabIds);
  362. if ( singleTab ) {
  363. tabIds = [tabIds];
  364. }
  365. for ( var tab of this.getAllSync() ) {
  366. var tabId = this.stack.get(getBrowserForTab(tab));
  367. if ( !tabId ) {
  368. continue;
  369. }
  370. if ( tabIds.indexOf(tabId) !== -1 ) {
  371. tabs.push(tab);
  372. }
  373. if ( tabs.length >= tabIds.length ) {
  374. break;
  375. }
  376. }
  377. return singleTab ? tabs[0] || null : tabs;
  378. };
  379. /******************************************************************************/
  380. vAPI.tabs.get = function(tabId, callback) {
  381. var tab, win;
  382. if ( tabId === null ) {
  383. win = Services.wm.getMostRecentWindow('navigator:browser');
  384. tab = getTabBrowser(win).selectedTab;
  385. tabId = this.getTabId(tab);
  386. } else {
  387. tab = this.getTabsForIds(tabId);
  388. if ( tab ) {
  389. win = getOwnerWindow(tab);
  390. }
  391. }
  392. // For internal use
  393. if ( typeof callback !== 'function' ) {
  394. return tab;
  395. }
  396. if ( !tab ) {
  397. callback();
  398. return;
  399. }
  400. var windows = this.getWindows();
  401. var browser = getBrowserForTab(tab);
  402. var tabBrowser = getTabBrowser(win);
  403. var tabIndex = tabBrowser.browsers.indexOf(browser);
  404. var tabTitle = tab.label;
  405. callback({
  406. id: tabId,
  407. index: tabIndex,
  408. windowId: windows.indexOf(win),
  409. active: tab === tabBrowser.selectedTab,
  410. url: browser.currentURI.asciiSpec,
  411. title: tabTitle
  412. });
  413. };
  414. /******************************************************************************/
  415. vAPI.tabs.getAllSync = function(window) {
  416. var win, tab;
  417. var tabs = [];
  418. for ( win of this.getWindows() ) {
  419. if ( window && window !== win ) {
  420. continue;
  421. }
  422. var tabBrowser = getTabBrowser(win);
  423. if ( tabBrowser === null ) {
  424. continue;
  425. }
  426. for ( tab of tabBrowser.tabs ) {
  427. tabs.push(tab);
  428. }
  429. }
  430. return tabs;
  431. };
  432. /******************************************************************************/
  433. vAPI.tabs.getAll = function(callback) {
  434. var tabs = [];
  435. var win, tab;
  436. for ( win of this.getWindows() ) {
  437. var tabBrowser = getTabBrowser(win);
  438. if ( tabBrowser === null ) {
  439. continue;
  440. }
  441. for ( tab of tabBrowser.tabs ) {
  442. tabs.push({
  443. id: this.getTabId(tab),
  444. url: getBrowserForTab(tab).currentURI.asciiSpec
  445. });
  446. }
  447. }
  448. callback(tabs);
  449. };
  450. /******************************************************************************/
  451. vAPI.tabs.getWindows = function() {
  452. var winumerator = Services.wm.getEnumerator('navigator:browser');
  453. var windows = [];
  454. while ( winumerator.hasMoreElements() ) {
  455. var win = winumerator.getNext();
  456. if ( !win.closed ) {
  457. windows.push(win);
  458. }
  459. }
  460. return windows;
  461. };
  462. /******************************************************************************/
  463. // properties of the details object:
  464. // url: 'URL', // the address that will be opened
  465. // tabId: 1, // the tab is used if set, instead of creating a new one
  466. // index: -1, // undefined: end of the list, -1: following tab, or after index
  467. // active: false, // opens the tab in background - true and undefined: foreground
  468. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  469. vAPI.tabs.open = function(details) {
  470. if ( !details.url ) {
  471. return null;
  472. }
  473. // extension pages
  474. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  475. details.url = vAPI.getURL(details.url);
  476. }
  477. var win, tab, tabBrowser;
  478. if ( details.select ) {
  479. var URI = Services.io.newURI(details.url, null, null);
  480. for ( tab of this.getAllSync() ) {
  481. var browser = getBrowserForTab(tab);
  482. // Or simply .equals if we care about the fragment
  483. if ( URI.equalsExceptRef(browser.currentURI) === false ) {
  484. continue;
  485. }
  486. this.select(tab);
  487. return;
  488. }
  489. }
  490. if ( details.active === undefined ) {
  491. details.active = true;
  492. }
  493. if ( details.tabId ) {
  494. tab = this.getTabsForIds(details.tabId);
  495. if ( tab ) {
  496. getBrowserForTab(tab).loadURI(details.url);
  497. return;
  498. }
  499. }
  500. win = Services.wm.getMostRecentWindow('navigator:browser');
  501. tabBrowser = getTabBrowser(win);
  502. if ( details.index === -1 ) {
  503. details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
  504. }
  505. tab = tabBrowser.loadOneTab(details.url, {inBackground: !details.active});
  506. if ( details.index !== undefined ) {
  507. tabBrowser.moveTabTo(tab, details.index);
  508. }
  509. };
  510. /******************************************************************************/
  511. // Replace the URL of a tab. Noop if the tab does not exist.
  512. vAPI.tabs.replace = function(tabId, url) {
  513. var targetURL = url;
  514. // extension pages
  515. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  516. targetURL = vAPI.getURL(targetURL);
  517. }
  518. var tab = this.getTabsForIds(tabId);
  519. if ( tab ) {
  520. getBrowserForTab(tab).loadURI(targetURL);
  521. }
  522. };
  523. /******************************************************************************/
  524. vAPI.tabs._remove = function(tab, tabBrowser) {
  525. tabBrowser.removeTab(tab);
  526. };
  527. /******************************************************************************/
  528. vAPI.tabs.remove = function(tabIds) {
  529. if ( !Array.isArray(tabIds) ) {
  530. tabIds = [tabIds];
  531. }
  532. var tabs = this.getTabsForIds(tabIds);
  533. if ( tabs.length === 0 ) {
  534. return;
  535. }
  536. for ( var tab of tabs ) {
  537. this._remove(tab, getTabBrowser(getOwnerWindow(tab)));
  538. }
  539. };
  540. /******************************************************************************/
  541. vAPI.tabs.reload = function(tabId) {
  542. var tab = this.get(tabId);
  543. if ( !tab ) {
  544. return;
  545. }
  546. getBrowserForTab(tab).webNavigation.reload(
  547. Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE
  548. );
  549. };
  550. /******************************************************************************/
  551. vAPI.tabs.select = function(tab) {
  552. tab = typeof tab === 'object' ? tab : this.get(tab);
  553. if ( !tab ) {
  554. return;
  555. }
  556. getTabBrowser(getOwnerWindow(tab)).selectedTab = tab;
  557. };
  558. /******************************************************************************/
  559. vAPI.tabs.injectScript = function(tabId, details, callback) {
  560. var tab = this.get(tabId);
  561. if ( !tab ) {
  562. return;
  563. }
  564. if ( typeof details.file !== 'string' ) {
  565. return;
  566. }
  567. details.file = vAPI.getURL(details.file);
  568. getBrowserForTab(tab).messageManager.sendAsyncMessage(
  569. location.host + ':broadcast',
  570. JSON.stringify({
  571. broadcast: true,
  572. channelName: 'vAPI',
  573. msg: {
  574. cmd: 'injectScript',
  575. details: details
  576. }
  577. })
  578. );
  579. if ( typeof callback === 'function' ) {
  580. setTimeout(callback, 13);
  581. }
  582. };
  583. /******************************************************************************/
  584. vAPI.setIcon = function(tabId, iconId, badge) {
  585. // If badge is undefined, then setIcon was called from the TabSelect event
  586. var win;
  587. if ( badge === undefined ) {
  588. win = iconId;
  589. } else {
  590. win = Services.wm.getMostRecentWindow('navigator:browser');
  591. }
  592. var curTabId = vAPI.tabs.getTabId(getTabBrowser(win).selectedTab);
  593. var tb = vAPI.toolbarButton;
  594. // from 'TabSelect' event
  595. if ( tabId === undefined ) {
  596. tabId = curTabId;
  597. } else if ( badge !== undefined ) {
  598. tb.tabs[tabId] = { badge: badge, img: iconId };
  599. }
  600. if ( tabId === curTabId ) {
  601. tb.updateState(win, tabId);
  602. }
  603. };
  604. /******************************************************************************/
  605. vAPI.messaging = {
  606. get globalMessageManager() {
  607. return Cc['@mozilla.org/globalmessagemanager;1']
  608. .getService(Ci.nsIMessageListenerManager);
  609. },
  610. frameScript: vAPI.getURL('frameScript.js'),
  611. listeners: {},
  612. defaultHandler: null,
  613. NOOPFUNC: function(){},
  614. UNHANDLED: 'vAPI.messaging.notHandled'
  615. };
  616. /******************************************************************************/
  617. vAPI.messaging.listen = function(listenerName, callback) {
  618. this.listeners[listenerName] = callback;
  619. };
  620. /******************************************************************************/
  621. vAPI.messaging.onMessage = function({target, data}) {
  622. var messageManager = target.messageManager;
  623. if ( !messageManager ) {
  624. // Message came from a popup, and its message manager is not usable.
  625. // So instead we broadcast to the parent window.
  626. messageManager = getOwnerWindow(
  627. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  628. ).messageManager;
  629. }
  630. var channelNameRaw = data.channelName;
  631. var pos = channelNameRaw.indexOf('|');
  632. var channelName = channelNameRaw.slice(pos + 1);
  633. var callback = vAPI.messaging.NOOPFUNC;
  634. if ( data.requestId !== undefined ) {
  635. callback = CallbackWrapper.factory(
  636. messageManager,
  637. channelName,
  638. channelNameRaw.slice(0, pos),
  639. data.requestId
  640. ).callback;
  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('uMatrix> 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. cleanupTasks.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. // This allows to avoid creating a closure for every single message which
  700. // expects an answer. Having a closure created each time a message is processed
  701. // has been always bothering me. Another benefit of the implementation here
  702. // is to reuse the callback proxy object, so less memory churning.
  703. //
  704. // https://developers.google.com/speed/articles/optimizing-javascript
  705. // "Creating a closure is significantly slower then creating an inner
  706. // function without a closure, and much slower than reusing a static
  707. // function"
  708. //
  709. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  710. // "the dreaded 'uniformly slow code' case where every function takes 1%
  711. // of CPU and you have to make one hundred separate performance optimizations
  712. // to improve performance at all"
  713. //
  714. // http://jsperf.com/closure-no-closure/2
  715. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  716. this.callback = this.proxy.bind(this); // bind once
  717. this.init(messageManager, channelName, listenerId, requestId);
  718. };
  719. CallbackWrapper.junkyard = [];
  720. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  721. var wrapper = CallbackWrapper.junkyard.pop();
  722. if ( wrapper ) {
  723. wrapper.init(messageManager, channelName, listenerId, requestId);
  724. return wrapper;
  725. }
  726. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  727. };
  728. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  729. this.messageManager = messageManager;
  730. this.channelName = channelName;
  731. this.listenerId = listenerId;
  732. this.requestId = requestId;
  733. };
  734. CallbackWrapper.prototype.proxy = function(response) {
  735. var message = JSON.stringify({
  736. requestId: this.requestId,
  737. channelName: this.channelName,
  738. msg: response !== undefined ? response : null
  739. });
  740. if ( this.messageManager.sendAsyncMessage ) {
  741. this.messageManager.sendAsyncMessage(this.listenerId, message);
  742. } else {
  743. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  744. }
  745. // Mark for reuse
  746. this.messageManager =
  747. this.channelName =
  748. this.requestId =
  749. this.listenerId = null;
  750. CallbackWrapper.junkyard.push(this);
  751. };
  752. /******************************************************************************/
  753. var httpRequestHeadersFactory = function(channel) {
  754. var entry = httpRequestHeadersFactory.junkyard.pop();
  755. if ( entry ) {
  756. return entry.init(channel);
  757. }
  758. return new HTTPRequestHeaders(channel);
  759. };
  760. httpRequestHeadersFactory.junkyard = [];
  761. var HTTPRequestHeaders = function(channel) {
  762. this.init(channel);
  763. };
  764. HTTPRequestHeaders.prototype.init = function(channel) {
  765. this.channel = channel;
  766. return this;
  767. };
  768. HTTPRequestHeaders.prototype.dispose = function() {
  769. this.channel = null;
  770. httpRequestHeadersFactory.junkyard.push(this);
  771. };
  772. HTTPRequestHeaders.prototype.getHeader = function(name) {
  773. try {
  774. return this.channel.getRequestHeader(name);
  775. } catch (e) {
  776. }
  777. return '';
  778. };
  779. HTTPRequestHeaders.prototype.setHeader = function(name, newValue, create) {
  780. var oldValue = this.getHeader(name);
  781. if ( newValue === oldValue ) {
  782. return false;
  783. }
  784. if ( oldValue === '' && create !== true ) {
  785. return false;
  786. }
  787. this.channel.setRequestHeader(name, newValue, false);
  788. return true;
  789. };
  790. /******************************************************************************/
  791. var httpObserver = {
  792. classDescription: 'net-channel-event-sinks for ' + location.host,
  793. classID: Components.ID('{dc8d6319-5f6e-4438-999e-53722db99e84}'),
  794. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  795. REQDATAKEY: location.host + 'reqdata',
  796. ABORT: Components.results.NS_BINDING_ABORTED,
  797. ACCEPT: Components.results.NS_SUCCEEDED,
  798. // Request types: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  799. frameTypeMap: {
  800. 6: 'main_frame',
  801. 7: 'sub_frame'
  802. },
  803. typeMap: {
  804. 1: 'other',
  805. 2: 'script',
  806. 3: 'image',
  807. 4: 'stylesheet',
  808. 5: 'object',
  809. 6: 'main_frame',
  810. 7: 'sub_frame',
  811. 10: 'ping',
  812. 11: 'xmlhttprequest',
  813. 12: 'object',
  814. 14: 'font',
  815. 16: 'websocket',
  816. 21: 'image'
  817. },
  818. lastRequest: [{}, {}],
  819. get componentRegistrar() {
  820. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  821. },
  822. get categoryManager() {
  823. return Cc['@mozilla.org/categorymanager;1']
  824. .getService(Ci.nsICategoryManager);
  825. },
  826. QueryInterface: (function() {
  827. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  828. return XPCOMUtils.generateQI([
  829. Ci.nsIFactory,
  830. Ci.nsIObserver,
  831. Ci.nsIChannelEventSink,
  832. Ci.nsISupportsWeakReference
  833. ]);
  834. })(),
  835. createInstance: function(outer, iid) {
  836. if ( outer ) {
  837. throw Components.results.NS_ERROR_NO_AGGREGATION;
  838. }
  839. return this.QueryInterface(iid);
  840. },
  841. register: function() {
  842. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  843. Services.obs.addObserver(this, 'http-on-opening-request', true);
  844. Services.obs.addObserver(this, 'http-on-examine-response', true);
  845. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  846. // Guard against stale instances not having been unregistered
  847. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  848. try {
  849. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  850. } catch (ex) {
  851. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  852. }
  853. }
  854. this.componentRegistrar.registerFactory(
  855. this.classID,
  856. this.classDescription,
  857. this.contractID,
  858. this
  859. );
  860. this.categoryManager.addCategoryEntry(
  861. 'net-channel-event-sinks',
  862. this.contractID,
  863. this.contractID,
  864. false,
  865. true
  866. );
  867. },
  868. unregister: function() {
  869. Services.obs.removeObserver(this, 'http-on-opening-request');
  870. Services.obs.removeObserver(this, 'http-on-examine-response');
  871. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  872. this.componentRegistrar.unregisterFactory(this.classID, this);
  873. this.categoryManager.deleteCategoryEntry(
  874. 'net-channel-event-sinks',
  875. this.contractID,
  876. false
  877. );
  878. },
  879. handlePopup: function(URI, tabId, sourceTabId) {
  880. if ( !sourceTabId ) {
  881. return false;
  882. }
  883. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  884. return false;
  885. }
  886. var result = vAPI.tabs.onPopup({
  887. targetTabId: tabId,
  888. openerTabId: sourceTabId,
  889. targetURL: URI.asciiSpec
  890. });
  891. return result === true;
  892. },
  893. handleRequest: function(channel, URI, details) {
  894. var type = this.typeMap[details.type] || 'other';
  895. var result;
  896. var callbackDetails = {
  897. frameId: details.frameId,
  898. hostname: URI.asciiHost,
  899. parentFrameId: details.parentFrameId,
  900. tabId: details.tabId,
  901. type: type,
  902. url: URI.asciiSpec
  903. };
  904. var onBeforeRequest = vAPI.net.onBeforeRequest;
  905. if ( !onBeforeRequest.types || onBeforeRequest.types.has(type) ) {
  906. result = onBeforeRequest.callback(callbackDetails);
  907. if ( typeof result === 'object' && result.cancel === true ) {
  908. channel.cancel(this.ABORT);
  909. return true;
  910. }
  911. // For the time being, will block instead of redirecting
  912. // TODO: figure a better way of blocking embedded frames.
  913. // Maybe blocking network requests, then having a content script
  914. // revisit the DOM to replace blocked frame with something more
  915. // friendly. Will see.
  916. if ( typeof result === 'object' && result.redirectUrl ) {
  917. channel.cancel(this.ABORT);
  918. return true;
  919. }
  920. }
  921. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  922. if ( !onBeforeSendHeaders.types || onBeforeSendHeaders.types.has(type) ) {
  923. callbackDetails.requestHeaders = httpRequestHeadersFactory(channel);
  924. result = onBeforeSendHeaders.callback(callbackDetails);
  925. callbackDetails.requestHeaders.dispose();
  926. if ( typeof result === 'object' && result.cancel === true ) {
  927. channel.cancel(this.ABORT);
  928. return true;
  929. }
  930. }
  931. return false;
  932. },
  933. observe: function(channel, topic) {
  934. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  935. return;
  936. }
  937. var URI = channel.URI;
  938. var channelData, type, result;
  939. if (
  940. topic === 'http-on-examine-response' ||
  941. topic === 'http-on-examine-cached-response'
  942. ) {
  943. if ( !(channel instanceof Ci.nsIWritablePropertyBag) ) {
  944. return;
  945. }
  946. try {
  947. channelData = channel.getProperty(this.REQDATAKEY);
  948. } catch (ex) {
  949. return;
  950. }
  951. if ( !channelData ) {
  952. return;
  953. }
  954. type = this.frameTypeMap[channelData[4]];
  955. if ( !type ) {
  956. return;
  957. }
  958. topic = 'Content-Security-Policy';
  959. try {
  960. result = channel.getResponseHeader(topic);
  961. } catch (ex) {
  962. result = null;
  963. }
  964. result = vAPI.net.onHeadersReceived.callback({
  965. hostname: URI.asciiHost,
  966. parentFrameId: channelData[1],
  967. responseHeaders: result ? [{name: topic, value: result}] : [],
  968. tabId: channelData[3],
  969. type: type,
  970. url: URI.asciiSpec
  971. });
  972. if ( result ) {
  973. channel.setResponseHeader(
  974. topic,
  975. result.responseHeaders.pop().value,
  976. true
  977. );
  978. }
  979. return;
  980. }
  981. // http-on-opening-request
  982. var lastRequest = this.lastRequest[0];
  983. if ( lastRequest.url !== URI.spec ) {
  984. if ( this.lastRequest[1].url === URI.spec ) {
  985. lastRequest = this.lastRequest[1];
  986. } else {
  987. lastRequest.url = null;
  988. }
  989. }
  990. if ( lastRequest.url === null ) {
  991. lastRequest.type = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  992. result = this.handleRequest(channel, URI, {
  993. tabId: vAPI.noTabId,
  994. type: lastRequest.type
  995. });
  996. if ( result === true ) {
  997. return;
  998. }
  999. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1000. return;
  1001. }
  1002. // Carry data for behind-the-scene redirects
  1003. channel.setProperty(
  1004. this.REQDATAKEY,
  1005. [lastRequest.type, vAPI.noTabId, null, 0, -1]
  1006. );
  1007. return;
  1008. }
  1009. // Important! When loading file via XHR for mirroring,
  1010. // the URL will be the same, so it could fall into an infinite loop
  1011. lastRequest.url = null;
  1012. if ( this.handleRequest(channel, URI, lastRequest) ) {
  1013. return;
  1014. }
  1015. // If request is not handled we may use the data in on-modify-request
  1016. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1017. channel.setProperty(this.REQDATAKEY, [
  1018. lastRequest.frameId,
  1019. lastRequest.parentFrameId,
  1020. lastRequest.sourceTabId,
  1021. lastRequest.tabId,
  1022. lastRequest.type
  1023. ]);
  1024. }
  1025. },
  1026. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1027. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1028. var result = this.ACCEPT;
  1029. // If error thrown, the redirect will fail
  1030. try {
  1031. var URI = newChannel.URI;
  1032. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1033. return;
  1034. }
  1035. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1036. return;
  1037. }
  1038. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1039. if ( this.handlePopup(URI, channelData[3], channelData[2]) ) {
  1040. result = this.ABORT;
  1041. return;
  1042. }
  1043. var details = {
  1044. frameId: channelData[0],
  1045. parentFrameId: channelData[1],
  1046. tabId: channelData[3],
  1047. type: channelData[4]
  1048. };
  1049. if ( this.handleRequest(newChannel, URI, details) ) {
  1050. result = this.ABORT;
  1051. return;
  1052. }
  1053. // Carry the data on in case of multiple redirects
  1054. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1055. newChannel.setProperty(this.REQDATAKEY, channelData);
  1056. }
  1057. } catch (ex) {
  1058. // console.error(ex);
  1059. } finally {
  1060. callback.onRedirectVerifyCallback(result);
  1061. }
  1062. }
  1063. };
  1064. /******************************************************************************/
  1065. vAPI.net = {};
  1066. /******************************************************************************/
  1067. vAPI.net.registerListeners = function() {
  1068. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1069. new Set(this.onBeforeRequest.types) :
  1070. null;
  1071. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1072. new Set(this.onBeforeSendHeaders.types) :
  1073. null;
  1074. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1075. var shouldLoadListener = function(e) {
  1076. var details = e.data;
  1077. var tabId = vAPI.tabs.getTabId(e.target);
  1078. var sourceTabId = null;
  1079. // Popup candidate
  1080. if ( details.openerURL ) {
  1081. for ( var tab of vAPI.tabs.getAllSync() ) {
  1082. var URI = getBrowserForTab(tab).currentURI;
  1083. // Probably isn't the best method to identify the source tab
  1084. if ( URI.spec !== details.openerURL ) {
  1085. continue;
  1086. }
  1087. sourceTabId = vAPI.tabs.getTabId(tab);
  1088. if ( sourceTabId === tabId ) {
  1089. sourceTabId = null;
  1090. continue;
  1091. }
  1092. URI = Services.io.newURI(details.url, null, null);
  1093. if ( httpObserver.handlePopup(URI, tabId, sourceTabId) ) {
  1094. return;
  1095. }
  1096. break;
  1097. }
  1098. }
  1099. var lastRequest = httpObserver.lastRequest;
  1100. lastRequest[1] = lastRequest[0];
  1101. lastRequest[0] = {
  1102. frameId: details.frameId,
  1103. parentFrameId: details.parentFrameId,
  1104. sourceTabId: sourceTabId,
  1105. tabId: tabId,
  1106. type: details.type,
  1107. url: details.url
  1108. };
  1109. };
  1110. vAPI.messaging.globalMessageManager.addMessageListener(
  1111. shouldLoadListenerMessageName,
  1112. shouldLoadListener
  1113. );
  1114. var locationChangedListenerMessageName = location.host + ':locationChanged';
  1115. var locationChangedListener = function(e) {
  1116. var details = e.data;
  1117. var browser = e.target;
  1118. var tabId = vAPI.tabs.getTabId(browser);
  1119. //console.debug("nsIWebProgressListener: onLocationChange: " + details.url + " (" + details.flags + ")");
  1120. // LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
  1121. if ( details.flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT ) {
  1122. vAPI.tabs.onUpdated(tabId, {url: details.url}, {
  1123. frameId: 0,
  1124. tabId: tabId,
  1125. url: browser.currentURI.asciiSpec
  1126. });
  1127. return;
  1128. }
  1129. // https://github.com/chrisaljoudi/uBlock/issues/105
  1130. // Allow any kind of pages
  1131. vAPI.tabs.onNavigation({
  1132. frameId: 0,
  1133. tabId: tabId,
  1134. url: details.url,
  1135. });
  1136. };
  1137. vAPI.messaging.globalMessageManager.addMessageListener(
  1138. locationChangedListenerMessageName,
  1139. locationChangedListener
  1140. );
  1141. httpObserver.register();
  1142. cleanupTasks.push(function() {
  1143. vAPI.messaging.globalMessageManager.removeMessageListener(
  1144. shouldLoadListenerMessageName,
  1145. shouldLoadListener
  1146. );
  1147. vAPI.messaging.globalMessageManager.removeMessageListener(
  1148. locationChangedListenerMessageName,
  1149. locationChangedListener
  1150. );
  1151. httpObserver.unregister();
  1152. });
  1153. };
  1154. /******************************************************************************/
  1155. vAPI.toolbarButton = {
  1156. id: location.host + '-button',
  1157. type: 'view',
  1158. viewId: location.host + '-panel',
  1159. label: vAPI.app.name,
  1160. tooltiptext: vAPI.app.name,
  1161. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  1162. };
  1163. /******************************************************************************/
  1164. // Toolbar button UI for desktop Firefox
  1165. vAPI.toolbarButton.init = function() {
  1166. var CustomizableUI;
  1167. try {
  1168. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1169. } catch (ex) {
  1170. return;
  1171. }
  1172. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  1173. this.styleURI = [
  1174. '#' + this.id + ' {',
  1175. 'list-style-image: url(',
  1176. vAPI.getURL('img/browsericons/icon19-off.png'),
  1177. ');',
  1178. '}',
  1179. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1180. 'width: 160px;',
  1181. 'height: 290px;',
  1182. 'overflow: hidden !important;',
  1183. '}'
  1184. ];
  1185. var platformVersion = Services.appinfo.platformVersion;
  1186. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1187. this.styleURI.push(
  1188. '#' + this.id + '[badge]:not([badge=""])::after {',
  1189. 'position: absolute;',
  1190. 'margin-left: -16px;',
  1191. 'margin-top: 3px;',
  1192. 'padding: 1px 2px;',
  1193. 'font-size: 9px;',
  1194. 'font-weight: bold;',
  1195. 'color: #fff;',
  1196. 'background: #000;',
  1197. 'content: attr(badge);',
  1198. '}'
  1199. );
  1200. } else {
  1201. this.CUIEvents = {};
  1202. var updateBadge = function() {
  1203. var wId = vAPI.toolbarButton.id;
  1204. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  1205. for ( var win of vAPI.tabs.getWindows() ) {
  1206. var button = win.document.getElementById(wId);
  1207. if ( buttonInPanel ) {
  1208. button.classList.remove('badged-button');
  1209. continue;
  1210. }
  1211. if ( button === null ) {
  1212. continue;
  1213. }
  1214. button.classList.add('badged-button');
  1215. }
  1216. if ( buttonInPanel ) {
  1217. return;
  1218. }
  1219. // Anonymous elements need some time to be reachable
  1220. setTimeout(this.updateBadgeStyle, 250);
  1221. }.bind(this.CUIEvents);
  1222. this.CUIEvents.onCustomizeEnd = updateBadge;
  1223. this.CUIEvents.onWidgetUnderflow = updateBadge;
  1224. this.CUIEvents.updateBadgeStyle = function() {
  1225. var css = [
  1226. 'background: #000',
  1227. 'color: #fff'
  1228. ].join(';');
  1229. for ( var win of vAPI.tabs.getWindows() ) {
  1230. var button = win.document.getElementById(vAPI.toolbarButton.id);
  1231. if ( button === null ) {
  1232. continue;
  1233. }
  1234. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1235. button,
  1236. 'class',
  1237. 'toolbarbutton-badge'
  1238. );
  1239. if ( !badge ) {
  1240. return;
  1241. }
  1242. badge.style.cssText = css;
  1243. }
  1244. };
  1245. this.onCreated = function(button) {
  1246. button.setAttribute('badge', '');
  1247. setTimeout(updateBadge, 250);
  1248. };
  1249. CustomizableUI.addListener(this.CUIEvents);
  1250. }
  1251. this.styleURI = Services.io.newURI(
  1252. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  1253. null,
  1254. null
  1255. );
  1256. this.closePopup = function({target}) {
  1257. CustomizableUI.hidePanelForNode(
  1258. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  1259. );
  1260. };
  1261. CustomizableUI.createWidget(this);
  1262. vAPI.messaging.globalMessageManager.addMessageListener(
  1263. location.host + ':closePopup',
  1264. this.closePopup
  1265. );
  1266. cleanupTasks.push(function() {
  1267. if ( this.CUIEvents ) {
  1268. CustomizableUI.removeListener(this.CUIEvents);
  1269. }
  1270. CustomizableUI.destroyWidget(this.id);
  1271. vAPI.messaging.globalMessageManager.removeMessageListener(
  1272. location.host + ':closePopup',
  1273. this.closePopup
  1274. );
  1275. for ( var win of vAPI.tabs.getWindows() ) {
  1276. var panel = win.document.getElementById(this.viewId);
  1277. panel.parentNode.removeChild(panel);
  1278. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1279. .getInterface(Ci.nsIDOMWindowUtils)
  1280. .removeSheet(this.styleURI, 1);
  1281. }
  1282. }.bind(this));
  1283. this.init = null;
  1284. };
  1285. /******************************************************************************/
  1286. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  1287. var panel = doc.createElement('panelview');
  1288. panel.setAttribute('id', this.viewId);
  1289. var iframe = doc.createElement('iframe');
  1290. iframe.setAttribute('type', 'content');
  1291. doc.getElementById('PanelUI-multiView')
  1292. .appendChild(panel)
  1293. .appendChild(iframe);
  1294. var updateTimer = null;
  1295. var delayedResize = function() {
  1296. if ( updateTimer ) {
  1297. return;
  1298. }
  1299. updateTimer = setTimeout(resizePopup, 10);
  1300. };
  1301. var resizePopup = function() {
  1302. updateTimer = null;
  1303. var body = iframe.contentDocument.body;
  1304. panel.parentNode.style.maxWidth = 'none';
  1305. // We set a limit for height
  1306. var height = Math.min(body.clientHeight, 600);
  1307. var width = body.clientWidth;
  1308. // https://github.com/chrisaljoudi/uBlock/issues/730
  1309. // Voodoo programming: this recipe works
  1310. panel.style.height = iframe.style.height = height.toString() + 'px';
  1311. panel.style.width = iframe.style.width = width.toString() + 'px';
  1312. if ( iframe.clientHeight !== height || iframe.clientWidth !== width ) {
  1313. delayedResize();
  1314. }
  1315. };
  1316. var onPopupReady = function() {
  1317. var win = this.contentWindow;
  1318. if ( !win || win.location.host !== location.host ) {
  1319. return;
  1320. }
  1321. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1322. attributes: true,
  1323. characterData: true,
  1324. subtree: true
  1325. });
  1326. delayedResize();
  1327. };
  1328. iframe.addEventListener('load', onPopupReady, true);
  1329. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1330. .getInterface(Ci.nsIDOMWindowUtils)
  1331. .loadSheet(this.styleURI, 1);
  1332. };
  1333. /******************************************************************************/
  1334. vAPI.toolbarButton.onViewShowing = function({target}) {
  1335. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1336. };
  1337. /******************************************************************************/
  1338. vAPI.toolbarButton.onViewHiding = function({target}) {
  1339. target.parentNode.style.maxWidth = '';
  1340. target.firstChild.setAttribute('src', 'about:blank');
  1341. };
  1342. /******************************************************************************/
  1343. vAPI.toolbarButton.updateState = function(win, tabId) {
  1344. var button = win.document.getElementById(this.id);
  1345. if ( !button ) {
  1346. return;
  1347. }
  1348. var icon = this.tabs[tabId];
  1349. button.setAttribute('badge', icon && icon.badge || '');
  1350. var iconId = icon && icon.img ? icon.img : 'off';
  1351. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1352. button.style.listStyleImage = icon;
  1353. };
  1354. /******************************************************************************/
  1355. vAPI.toolbarButton.init();
  1356. /******************************************************************************/
  1357. vAPI.contextMenu = {
  1358. contextMap: {
  1359. frame: 'inFrame',
  1360. link: 'onLink',
  1361. image: 'onImage',
  1362. audio: 'onAudio',
  1363. video: 'onVideo',
  1364. editable: 'onEditableArea'
  1365. }
  1366. };
  1367. /******************************************************************************/
  1368. vAPI.contextMenu.displayMenuItem = function({target}) {
  1369. var doc = target.ownerDocument;
  1370. var gContextMenu = doc.defaultView.gContextMenu;
  1371. if ( !gContextMenu.browser ) {
  1372. return;
  1373. }
  1374. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1375. var currentURI = gContextMenu.browser.currentURI;
  1376. // https://github.com/chrisaljoudi/uBlock/issues/105
  1377. // TODO: Should the element picker works on any kind of pages?
  1378. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1379. menuitem.hidden = true;
  1380. return;
  1381. }
  1382. var ctx = vAPI.contextMenu.contexts;
  1383. if ( !ctx ) {
  1384. menuitem.hidden = false;
  1385. return;
  1386. }
  1387. var ctxMap = vAPI.contextMenu.contextMap;
  1388. for ( var context of ctx ) {
  1389. if (
  1390. context === 'page' &&
  1391. !gContextMenu.onLink &&
  1392. !gContextMenu.onImage &&
  1393. !gContextMenu.onEditableArea &&
  1394. !gContextMenu.inFrame &&
  1395. !gContextMenu.onVideo &&
  1396. !gContextMenu.onAudio
  1397. ) {
  1398. menuitem.hidden = false;
  1399. return;
  1400. }
  1401. if ( gContextMenu[ctxMap[context]] ) {
  1402. menuitem.hidden = false;
  1403. return;
  1404. }
  1405. }
  1406. menuitem.hidden = true;
  1407. };
  1408. /******************************************************************************/
  1409. vAPI.contextMenu.register = function(doc) {
  1410. if ( !this.menuItemId ) {
  1411. return;
  1412. }
  1413. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1414. var menuitem = doc.createElement('menuitem');
  1415. menuitem.setAttribute('id', this.menuItemId);
  1416. menuitem.setAttribute('label', this.menuLabel);
  1417. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  1418. menuitem.setAttribute('class', 'menuitem-iconic');
  1419. menuitem.addEventListener('command', this.onCommand);
  1420. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1421. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1422. };
  1423. /******************************************************************************/
  1424. vAPI.contextMenu.unregister = function(doc) {
  1425. if ( !this.menuItemId ) {
  1426. return;
  1427. }
  1428. var menuitem = doc.getElementById(this.menuItemId);
  1429. var contextMenu = menuitem.parentNode;
  1430. menuitem.removeEventListener('command', this.onCommand);
  1431. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1432. contextMenu.removeChild(menuitem);
  1433. };
  1434. /******************************************************************************/
  1435. vAPI.contextMenu.create = function(details, callback) {
  1436. this.menuItemId = details.id;
  1437. this.menuLabel = details.title;
  1438. this.contexts = details.contexts;
  1439. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1440. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1441. } else {
  1442. // default in Chrome
  1443. this.contexts = ['page'];
  1444. }
  1445. this.onCommand = function() {
  1446. var gContextMenu = getOwnerWindow(this).gContextMenu;
  1447. var details = {
  1448. menuItemId: this.id
  1449. };
  1450. if ( gContextMenu.inFrame ) {
  1451. details.tagName = 'iframe';
  1452. // Probably won't work with e10s
  1453. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1454. } else if ( gContextMenu.onImage ) {
  1455. details.tagName = 'img';
  1456. details.srcUrl = gContextMenu.mediaURL;
  1457. } else if ( gContextMenu.onAudio ) {
  1458. details.tagName = 'audio';
  1459. details.srcUrl = gContextMenu.mediaURL;
  1460. } else if ( gContextMenu.onVideo ) {
  1461. details.tagName = 'video';
  1462. details.srcUrl = gContextMenu.mediaURL;
  1463. } else if ( gContextMenu.onLink ) {
  1464. details.tagName = 'a';
  1465. details.linkUrl = gContextMenu.linkURL;
  1466. }
  1467. callback(details, {
  1468. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1469. url: gContextMenu.browser.currentURI.asciiSpec
  1470. });
  1471. };
  1472. for ( var win of vAPI.tabs.getWindows() ) {
  1473. this.register(win.document);
  1474. }
  1475. };
  1476. /******************************************************************************/
  1477. vAPI.contextMenu.remove = function() {
  1478. for ( var win of vAPI.tabs.getWindows() ) {
  1479. this.unregister(win.document);
  1480. }
  1481. this.menuItemId = null;
  1482. this.menuLabel = null;
  1483. this.contexts = null;
  1484. this.onCommand = null;
  1485. };
  1486. /******************************************************************************/
  1487. var optionsObserver = {
  1488. addonId: 'uMatrix@raymondhill.net',
  1489. register: function() {
  1490. Services.obs.addObserver(this, 'addon-options-displayed', false);
  1491. cleanupTasks.push(this.unregister.bind(this));
  1492. var browser = getBrowserForTab(vAPI.tabs.get(null));
  1493. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  1494. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  1495. }
  1496. },
  1497. unregister: function() {
  1498. Services.obs.removeObserver(this, 'addon-options-displayed');
  1499. },
  1500. setupOptionsButton: function(doc, id, page) {
  1501. var button = doc.getElementById(id);
  1502. if ( button === null ) {
  1503. return;
  1504. }
  1505. button.addEventListener('command', function() {
  1506. vAPI.tabs.open({ url: page, index: -1 });
  1507. });
  1508. button.label = vAPI.i18n(id);
  1509. },
  1510. observe: function(doc, topic, addonId) {
  1511. if ( addonId !== this.addonId ) {
  1512. return;
  1513. }
  1514. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  1515. this.setupOptionsButton(doc, 'showNetworkLogButton', 'devtools.html');
  1516. }
  1517. };
  1518. optionsObserver.register();
  1519. /******************************************************************************/
  1520. vAPI.lastError = function() {
  1521. return null;
  1522. };
  1523. /******************************************************************************/
  1524. // This is called only once, when everything has been loaded in memory after
  1525. // the extension was launched. It can be used to inject content scripts
  1526. // in already opened web pages, to remove whatever nuisance could make it to
  1527. // the web pages before uBlock was ready.
  1528. vAPI.onLoadAllCompleted = function() {
  1529. var µb = µBlock;
  1530. for ( var tab of this.tabs.getAllSync() ) {
  1531. // We're insterested in only the tabs that were already loaded
  1532. var tabId = this.tabs.getTabId(tab);
  1533. var browser = getBrowserForTab(tab);
  1534. µb.tabContextManager.commit(tabId, browser.currentURI.asciiSpec);
  1535. µb.bindTabToPageStats(tabId, browser.currentURI.asciiSpec);
  1536. browser.messageManager.sendAsyncMessage(
  1537. location.host + '-load-completed'
  1538. );
  1539. }
  1540. };
  1541. /******************************************************************************/
  1542. // Likelihood is that we do not have to punycode: given punycode overhead,
  1543. // it's faster to check and skip than do it unconditionally all the time.
  1544. var punycodeHostname = punycode.toASCII;
  1545. var isNotASCII = /[^\x21-\x7F]/;
  1546. vAPI.punycodeHostname = function(hostname) {
  1547. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1548. };
  1549. vAPI.punycodeURL = function(url) {
  1550. if ( isNotASCII.test(url) ) {
  1551. return Services.io.newURI(url, null, null).asciiSpec;
  1552. }
  1553. return url;
  1554. };
  1555. /******************************************************************************/
  1556. /******************************************************************************/
  1557. vAPI.browserCache = {};
  1558. /******************************************************************************/
  1559. vAPI.browserCache.clearByTime = function(since) {
  1560. // TODO
  1561. };
  1562. vAPI.browserCache.clearByOrigin = function(/* domain */) {
  1563. // TODO
  1564. };
  1565. /******************************************************************************/
  1566. vAPI.cookies = {};
  1567. /******************************************************************************/
  1568. vAPI.cookies.registerListeners = function() {
  1569. // TODO
  1570. };
  1571. /******************************************************************************/
  1572. vAPI.cookies.getAll = function(callback) {
  1573. // TODO
  1574. if ( typeof callback === 'function' ) {
  1575. callback([]);
  1576. }
  1577. };
  1578. /******************************************************************************/
  1579. vAPI.cookies.remove = function(details, callback) {
  1580. // TODO
  1581. if ( typeof callback === 'function' ) {
  1582. callback(null);
  1583. }
  1584. };
  1585. /******************************************************************************/
  1586. })();
  1587. /******************************************************************************/