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.

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