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.

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