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.

2099 lines
62 KiB

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