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.

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