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.

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