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.

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