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.

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