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.

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