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.

2041 lines
60 KiB

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