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.

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