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.

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