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.

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