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.

2018 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. .getInterface(Ci.nsIWebNavigation)
  1011. .QueryInterface(Ci.nsIDocShell)
  1012. .rootTreeItem
  1013. .QueryInterface(Ci.nsIInterfaceRequestor)
  1014. .getInterface(Ci.nsIDOMWindow)
  1015. .gBrowser
  1016. .getBrowserForContentWindow(aWindow)
  1017. );
  1018. }
  1019. } catch (ex) {
  1020. //console.error(ex);
  1021. }
  1022. return vAPI.noTabId;
  1023. },
  1024. observe: function(channel, topic) {
  1025. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  1026. return;
  1027. }
  1028. var URI = channel.URI;
  1029. var channelData, tabId, rawtype;
  1030. if (
  1031. topic === 'http-on-examine-response' ||
  1032. topic === 'http-on-examine-cached-response'
  1033. ) {
  1034. channelData = this.channelDataFromChannel(channel);
  1035. if ( channelData === null ) {
  1036. return;
  1037. }
  1038. var type = this.frameTypeMap[channelData[1]];
  1039. if ( !type ) {
  1040. return;
  1041. }
  1042. topic = 'Content-Security-Policy';
  1043. var result;
  1044. try {
  1045. result = channel.getResponseHeader(topic);
  1046. } catch (ex) {
  1047. result = null;
  1048. }
  1049. result = vAPI.net.onHeadersReceived.callback({
  1050. hostname: URI.asciiHost,
  1051. parentFrameId: type === 'main_frame' ? -1 : 0,
  1052. responseHeaders: result ? [{name: topic, value: result}] : [],
  1053. tabId: channelData[0],
  1054. type: type,
  1055. url: URI.asciiSpec
  1056. });
  1057. if ( result ) {
  1058. channel.setResponseHeader(
  1059. topic,
  1060. result.responseHeaders.pop().value,
  1061. true
  1062. );
  1063. }
  1064. return;
  1065. }
  1066. if ( topic === 'http-on-modify-request' ) {
  1067. channelData = this.channelDataFromChannel(channel);
  1068. if ( channelData === null ) {
  1069. return;
  1070. }
  1071. this.handleRequestHeaders(channel, URI, channelData[0], channelData[1]);
  1072. return;
  1073. }
  1074. // http-on-opening-request
  1075. tabId = this.tabIdFromChannel(channel);
  1076. rawtype = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  1077. if ( this.handleRequest(channel, URI, tabId, rawtype) === true ) {
  1078. return;
  1079. }
  1080. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1081. return;
  1082. }
  1083. // Carry data for behind-the-scene redirects
  1084. channel.setProperty(this.REQDATAKEY, [tabId, rawtype]);
  1085. },
  1086. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1087. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1088. var result = this.ACCEPT;
  1089. // If error thrown, the redirect will fail
  1090. try {
  1091. var URI = newChannel.URI;
  1092. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1093. return;
  1094. }
  1095. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1096. return;
  1097. }
  1098. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1099. if ( this.handleRequest(newChannel, URI, channelData[0], channelData[1]) ) {
  1100. result = this.ABORT;
  1101. return;
  1102. }
  1103. // Carry the data on in case of multiple redirects
  1104. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1105. newChannel.setProperty(this.REQDATAKEY, channelData);
  1106. }
  1107. } catch (ex) {
  1108. // console.error(ex);
  1109. } finally {
  1110. callback.onRedirectVerifyCallback(result);
  1111. }
  1112. }
  1113. };
  1114. /******************************************************************************/
  1115. vAPI.net = {};
  1116. /******************************************************************************/
  1117. vAPI.net.registerListeners = function() {
  1118. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1119. new Set(this.onBeforeRequest.types) :
  1120. null;
  1121. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1122. new Set(this.onBeforeSendHeaders.types) :
  1123. null;
  1124. httpObserver.register();
  1125. cleanupTasks.push(function() {
  1126. httpObserver.unregister();
  1127. });
  1128. };
  1129. /******************************************************************************/
  1130. vAPI.toolbarButton = {
  1131. id: location.host + '-button',
  1132. type: 'view',
  1133. viewId: location.host + '-panel',
  1134. label: vAPI.app.name,
  1135. tooltiptext: vAPI.app.name,
  1136. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  1137. };
  1138. /******************************************************************************/
  1139. // Toolbar button UI for desktop Firefox
  1140. vAPI.toolbarButton.init = function() {
  1141. var CustomizableUI;
  1142. try {
  1143. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1144. } catch (ex) {
  1145. return;
  1146. }
  1147. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  1148. this.styleURI = [
  1149. '#' + this.id + ' {',
  1150. 'list-style-image: url(',
  1151. vAPI.getURL('img/browsericons/icon19-off.png'),
  1152. ');',
  1153. '}',
  1154. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1155. 'width: 160px;',
  1156. 'height: 290px;',
  1157. 'overflow: hidden !important;',
  1158. '}'
  1159. ];
  1160. var platformVersion = Services.appinfo.platformVersion;
  1161. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1162. this.styleURI.push(
  1163. '#' + this.id + '[badge]:not([badge=""])::after {',
  1164. 'position: absolute;',
  1165. 'margin-left: -16px;',
  1166. 'margin-top: 3px;',
  1167. 'padding: 1px 2px;',
  1168. 'font-size: 9px;',
  1169. 'font-weight: bold;',
  1170. 'color: #fff;',
  1171. 'background: #000;',
  1172. 'content: attr(badge);',
  1173. '}'
  1174. );
  1175. } else {
  1176. this.CUIEvents = {};
  1177. var updateBadge = function() {
  1178. var wId = vAPI.toolbarButton.id;
  1179. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  1180. for ( var win of vAPI.tabs.getWindows() ) {
  1181. var button = win.document.getElementById(wId);
  1182. if ( buttonInPanel ) {
  1183. button.classList.remove('badged-button');
  1184. continue;
  1185. }
  1186. if ( button === null ) {
  1187. continue;
  1188. }
  1189. button.classList.add('badged-button');
  1190. }
  1191. if ( buttonInPanel ) {
  1192. return;
  1193. }
  1194. // Anonymous elements need some time to be reachable
  1195. vAPI.setTimeout(this.updateBadgeStyle, 250);
  1196. }.bind(this.CUIEvents);
  1197. this.CUIEvents.onCustomizeEnd = updateBadge;
  1198. this.CUIEvents.onWidgetUnderflow = updateBadge;
  1199. this.CUIEvents.updateBadgeStyle = function() {
  1200. var css = [
  1201. 'background: #000',
  1202. 'color: #fff'
  1203. ].join(';');
  1204. for ( var win of vAPI.tabs.getWindows() ) {
  1205. var button = win.document.getElementById(vAPI.toolbarButton.id);
  1206. if ( button === null ) {
  1207. continue;
  1208. }
  1209. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1210. button,
  1211. 'class',
  1212. 'toolbarbutton-badge'
  1213. );
  1214. if ( !badge ) {
  1215. return;
  1216. }
  1217. badge.style.cssText = css;
  1218. }
  1219. };
  1220. this.onCreated = function(button) {
  1221. button.setAttribute('badge', '');
  1222. vAPI.setTimeout(updateBadge, 250);
  1223. };
  1224. CustomizableUI.addListener(this.CUIEvents);
  1225. }
  1226. this.styleURI = Services.io.newURI(
  1227. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  1228. null,
  1229. null
  1230. );
  1231. this.closePopup = function({target}) {
  1232. CustomizableUI.hidePanelForNode(
  1233. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  1234. );
  1235. };
  1236. CustomizableUI.createWidget(this);
  1237. vAPI.messaging.globalMessageManager.addMessageListener(
  1238. location.host + ':closePopup',
  1239. this.closePopup
  1240. );
  1241. cleanupTasks.push(function() {
  1242. if ( this.CUIEvents ) {
  1243. CustomizableUI.removeListener(this.CUIEvents);
  1244. }
  1245. CustomizableUI.destroyWidget(this.id);
  1246. vAPI.messaging.globalMessageManager.removeMessageListener(
  1247. location.host + ':closePopup',
  1248. this.closePopup
  1249. );
  1250. for ( var win of vAPI.tabs.getWindows() ) {
  1251. var panel = win.document.getElementById(this.viewId);
  1252. panel.parentNode.removeChild(panel);
  1253. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1254. .getInterface(Ci.nsIDOMWindowUtils)
  1255. .removeSheet(this.styleURI, 1);
  1256. }
  1257. }.bind(this));
  1258. this.init = null;
  1259. };
  1260. /******************************************************************************/
  1261. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  1262. var panel = doc.createElement('panelview');
  1263. panel.setAttribute('id', this.viewId);
  1264. var iframe = doc.createElement('iframe');
  1265. iframe.setAttribute('type', 'content');
  1266. iframe.setAttribute('overflow-x', 'hidden');
  1267. doc.getElementById('PanelUI-multiView')
  1268. .appendChild(panel)
  1269. .appendChild(iframe);
  1270. var updateTimer = null;
  1271. var delayedResize = function() {
  1272. if ( updateTimer ) {
  1273. return;
  1274. }
  1275. updateTimer = vAPI.setTimeout(resizePopup, 10);
  1276. };
  1277. var resizePopup = function() {
  1278. updateTimer = null;
  1279. var body = iframe.contentDocument.body;
  1280. panel.parentNode.style.maxWidth = 'none';
  1281. // We set a limit for height
  1282. var height = Math.min(body.clientHeight, 600);
  1283. var width = body.clientWidth;
  1284. // https://github.com/chrisaljoudi/uBlock/issues/730
  1285. // Voodoo programming: this recipe works
  1286. panel.style.setProperty('height', height + 'px');
  1287. iframe.style.setProperty('height', height + 'px');
  1288. // Adjust width for presence/absence of vertical scroll bar which may
  1289. // have appeared as a result of last operation.
  1290. panel.style.setProperty('width', width + 'px');
  1291. var cw = panel.clientWidth;
  1292. var dw = iframe.contentWindow.document.documentElement.clientWidth;
  1293. if ( cw !== dw ) {
  1294. width = 2 * cw - dw;
  1295. panel.style.setProperty('width', width + 'px');
  1296. }
  1297. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1298. delayedResize();
  1299. return;
  1300. }
  1301. };
  1302. var onPopupReady = function() {
  1303. var win = this.contentWindow;
  1304. if ( !win || win.location.host !== location.host ) {
  1305. return;
  1306. }
  1307. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1308. attributes: true,
  1309. characterData: true,
  1310. subtree: true
  1311. });
  1312. delayedResize();
  1313. };
  1314. iframe.addEventListener('load', onPopupReady, true);
  1315. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1316. .getInterface(Ci.nsIDOMWindowUtils)
  1317. .loadSheet(this.styleURI, 1);
  1318. };
  1319. /******************************************************************************/
  1320. vAPI.toolbarButton.onViewShowing = function({target}) {
  1321. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1322. };
  1323. /******************************************************************************/
  1324. vAPI.toolbarButton.onViewHiding = function({target}) {
  1325. target.parentNode.style.maxWidth = '';
  1326. target.firstChild.setAttribute('src', 'about:blank');
  1327. };
  1328. /******************************************************************************/
  1329. vAPI.toolbarButton.updateState = function(win, tabId) {
  1330. var button = win.document.getElementById(this.id);
  1331. if ( !button ) {
  1332. return;
  1333. }
  1334. var icon = this.tabs[tabId];
  1335. button.setAttribute('badge', icon && icon.badge || '');
  1336. var iconId = icon && icon.img ? icon.img : 'off';
  1337. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1338. button.style.listStyleImage = icon;
  1339. };
  1340. /******************************************************************************/
  1341. vAPI.toolbarButton.init();
  1342. /******************************************************************************/
  1343. /******************************************************************************/
  1344. vAPI.contextMenu = {
  1345. contextMap: {
  1346. frame: 'inFrame',
  1347. link: 'onLink',
  1348. image: 'onImage',
  1349. audio: 'onAudio',
  1350. video: 'onVideo',
  1351. editable: 'onEditableArea'
  1352. }
  1353. };
  1354. /******************************************************************************/
  1355. vAPI.contextMenu.displayMenuItem = function({target}) {
  1356. var doc = target.ownerDocument;
  1357. var gContextMenu = doc.defaultView.gContextMenu;
  1358. if ( !gContextMenu.browser ) {
  1359. return;
  1360. }
  1361. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1362. var currentURI = gContextMenu.browser.currentURI;
  1363. // https://github.com/chrisaljoudi/uBlock/issues/105
  1364. // TODO: Should the element picker works on any kind of pages?
  1365. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1366. menuitem.hidden = true;
  1367. return;
  1368. }
  1369. var ctx = vAPI.contextMenu.contexts;
  1370. if ( !ctx ) {
  1371. menuitem.hidden = false;
  1372. return;
  1373. }
  1374. var ctxMap = vAPI.contextMenu.contextMap;
  1375. for ( var context of ctx ) {
  1376. if (
  1377. context === 'page' &&
  1378. !gContextMenu.onLink &&
  1379. !gContextMenu.onImage &&
  1380. !gContextMenu.onEditableArea &&
  1381. !gContextMenu.inFrame &&
  1382. !gContextMenu.onVideo &&
  1383. !gContextMenu.onAudio
  1384. ) {
  1385. menuitem.hidden = false;
  1386. return;
  1387. }
  1388. if ( gContextMenu[ctxMap[context]] ) {
  1389. menuitem.hidden = false;
  1390. return;
  1391. }
  1392. }
  1393. menuitem.hidden = true;
  1394. };
  1395. /******************************************************************************/
  1396. vAPI.contextMenu.register = function(doc) {
  1397. if ( !this.menuItemId ) {
  1398. return;
  1399. }
  1400. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1401. var menuitem = doc.createElement('menuitem');
  1402. menuitem.setAttribute('id', this.menuItemId);
  1403. menuitem.setAttribute('label', this.menuLabel);
  1404. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  1405. menuitem.setAttribute('class', 'menuitem-iconic');
  1406. menuitem.addEventListener('command', this.onCommand);
  1407. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1408. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1409. };
  1410. /******************************************************************************/
  1411. vAPI.contextMenu.unregister = function(doc) {
  1412. if ( !this.menuItemId ) {
  1413. return;
  1414. }
  1415. var menuitem = doc.getElementById(this.menuItemId);
  1416. var contextMenu = menuitem.parentNode;
  1417. menuitem.removeEventListener('command', this.onCommand);
  1418. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1419. contextMenu.removeChild(menuitem);
  1420. };
  1421. /******************************************************************************/
  1422. vAPI.contextMenu.create = function(details, callback) {
  1423. this.menuItemId = details.id;
  1424. this.menuLabel = details.title;
  1425. this.contexts = details.contexts;
  1426. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1427. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1428. } else {
  1429. // default in Chrome
  1430. this.contexts = ['page'];
  1431. }
  1432. this.onCommand = function() {
  1433. var gContextMenu = getOwnerWindow(this).gContextMenu;
  1434. var details = {
  1435. menuItemId: this.id
  1436. };
  1437. if ( gContextMenu.inFrame ) {
  1438. details.tagName = 'iframe';
  1439. // Probably won't work with e10s
  1440. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1441. } else if ( gContextMenu.onImage ) {
  1442. details.tagName = 'img';
  1443. details.srcUrl = gContextMenu.mediaURL;
  1444. } else if ( gContextMenu.onAudio ) {
  1445. details.tagName = 'audio';
  1446. details.srcUrl = gContextMenu.mediaURL;
  1447. } else if ( gContextMenu.onVideo ) {
  1448. details.tagName = 'video';
  1449. details.srcUrl = gContextMenu.mediaURL;
  1450. } else if ( gContextMenu.onLink ) {
  1451. details.tagName = 'a';
  1452. details.linkUrl = gContextMenu.linkURL;
  1453. }
  1454. callback(details, {
  1455. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1456. url: gContextMenu.browser.currentURI.asciiSpec
  1457. });
  1458. };
  1459. for ( var win of vAPI.tabs.getWindows() ) {
  1460. this.register(win.document);
  1461. }
  1462. };
  1463. /******************************************************************************/
  1464. vAPI.contextMenu.remove = function() {
  1465. for ( var win of vAPI.tabs.getWindows() ) {
  1466. this.unregister(win.document);
  1467. }
  1468. this.menuItemId = null;
  1469. this.menuLabel = null;
  1470. this.contexts = null;
  1471. this.onCommand = null;
  1472. };
  1473. /******************************************************************************/
  1474. /******************************************************************************/
  1475. var optionsObserver = {
  1476. addonId: 'uMatrix@raymondhill.net',
  1477. register: function() {
  1478. Services.obs.addObserver(this, 'addon-options-displayed', false);
  1479. cleanupTasks.push(this.unregister.bind(this));
  1480. var browser = getBrowserForTab(vAPI.tabs.get(null));
  1481. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  1482. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  1483. }
  1484. },
  1485. unregister: function() {
  1486. Services.obs.removeObserver(this, 'addon-options-displayed');
  1487. },
  1488. setupOptionsButton: function(doc, id, page) {
  1489. var button = doc.getElementById(id);
  1490. if ( button === null ) {
  1491. return;
  1492. }
  1493. button.addEventListener('command', function() {
  1494. vAPI.tabs.open({ url: page, index: -1 });
  1495. });
  1496. button.label = vAPI.i18n(id);
  1497. },
  1498. observe: function(doc, topic, addonId) {
  1499. if ( addonId !== this.addonId ) {
  1500. return;
  1501. }
  1502. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  1503. this.setupOptionsButton(doc, 'showLoggerButton', 'logger-ui.html');
  1504. }
  1505. };
  1506. optionsObserver.register();
  1507. /******************************************************************************/
  1508. /******************************************************************************/
  1509. vAPI.lastError = function() {
  1510. return null;
  1511. };
  1512. /******************************************************************************/
  1513. /******************************************************************************/
  1514. // This is called only once, when everything has been loaded in memory after
  1515. // the extension was launched. It can be used to inject content scripts
  1516. // in already opened web pages, to remove whatever nuisance could make it to
  1517. // the web pages before uBlock was ready.
  1518. vAPI.onLoadAllCompleted = function() {
  1519. for ( var tab of this.tabs.getAllSync() ) {
  1520. // We're insterested in only the tabs that were already loaded
  1521. getBrowserForTab(tab).messageManager.sendAsyncMessage(
  1522. location.host + '-load-completed'
  1523. );
  1524. }
  1525. };
  1526. /******************************************************************************/
  1527. /******************************************************************************/
  1528. // Likelihood is that we do not have to punycode: given punycode overhead,
  1529. // it's faster to check and skip than do it unconditionally all the time.
  1530. var punycodeHostname = punycode.toASCII;
  1531. var isNotASCII = /[^\x21-\x7F]/;
  1532. vAPI.punycodeHostname = function(hostname) {
  1533. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1534. };
  1535. vAPI.punycodeURL = function(url) {
  1536. if ( isNotASCII.test(url) ) {
  1537. return Services.io.newURI(url, null, null).asciiSpec;
  1538. }
  1539. return url;
  1540. };
  1541. /******************************************************************************/
  1542. /******************************************************************************/
  1543. vAPI.browserData = {};
  1544. /******************************************************************************/
  1545. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  1546. vAPI.browserData.clearCache = function(callback) {
  1547. // PURGE_DISK_DATA_ONLY:1
  1548. // PURGE_DISK_ALL:2
  1549. // PURGE_EVERYTHING:3
  1550. // However I verified that not argument does clear the cache data.
  1551. Services.cache2.clear();
  1552. if ( typeof callback === 'function' ) {
  1553. callback();
  1554. }
  1555. };
  1556. /******************************************************************************/
  1557. vAPI.browserData.clearOrigin = function(/* domain */) {
  1558. // TODO
  1559. };
  1560. /******************************************************************************/
  1561. /******************************************************************************/
  1562. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  1563. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  1564. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  1565. vAPI.cookies = {};
  1566. /******************************************************************************/
  1567. vAPI.cookies.CookieEntry = function(ffCookie) {
  1568. this.domain = ffCookie.host;
  1569. this.name = ffCookie.name;
  1570. this.path = ffCookie.path;
  1571. this.secure = ffCookie.isSecure === true;
  1572. this.session = ffCookie.expires === 0;
  1573. this.value = ffCookie.value;
  1574. };
  1575. /******************************************************************************/
  1576. vAPI.cookies.start = function() {
  1577. Services.obs.addObserver(this, 'cookie-changed', false);
  1578. cleanupTasks.push(this.stop.bind(this));
  1579. };
  1580. /******************************************************************************/
  1581. vAPI.cookies.stop = function() {
  1582. Services.obs.removeObserver(this, 'cookie-changed');
  1583. };
  1584. /******************************************************************************/
  1585. vAPI.cookies.observe = function(subject, topic, reason) {
  1586. if ( topic !== 'cookie-changed' ) {
  1587. return;
  1588. }
  1589. if ( reason === 'deleted' || subject instanceof Ci.nsICookie2 === false ) {
  1590. return;
  1591. }
  1592. if ( typeof this.onChanged === 'function' ) {
  1593. this.onChanged(new this.CookieEntry(subject));
  1594. }
  1595. };
  1596. /******************************************************************************/
  1597. // Meant and expected to be asynchronous.
  1598. vAPI.cookies.getAll = function(callback) {
  1599. if ( typeof callback !== 'function' ) {
  1600. return;
  1601. }
  1602. var onAsync = function() {
  1603. var out = [];
  1604. var enumerator = Services.cookies.enumerator;
  1605. var ffcookie;
  1606. while ( enumerator.hasMoreElements() ) {
  1607. ffcookie = enumerator.getNext();
  1608. if ( ffcookie instanceof Ci.nsICookie ) {
  1609. out.push(new this.CookieEntry(ffcookie));
  1610. }
  1611. }
  1612. callback(out);
  1613. };
  1614. vAPI.setTimeout(onAsync.bind(this), 0);
  1615. };
  1616. /******************************************************************************/
  1617. vAPI.cookies.remove = function(details, callback) {
  1618. var uri = Services.io.newURI(details.url, null, null);
  1619. var cookies = Services.cookies;
  1620. cookies.remove(uri.asciiHost, details.name, uri.path, false);
  1621. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false);
  1622. if ( typeof callback === 'function' ) {
  1623. callback({
  1624. domain: uri.asciiHost,
  1625. name: details.name,
  1626. path: uri.path
  1627. });
  1628. }
  1629. };
  1630. /******************************************************************************/
  1631. /******************************************************************************/
  1632. })();
  1633. /******************************************************************************/