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.

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