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.

1940 lines
56 KiB

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