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.

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