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.

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