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.

1907 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
  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. /******************************************************************************/
  1335. vAPI.toolbarButton.init();
  1336. /******************************************************************************/
  1337. vAPI.contextMenu = {
  1338. contextMap: {
  1339. frame: 'inFrame',
  1340. link: 'onLink',
  1341. image: 'onImage',
  1342. audio: 'onAudio',
  1343. video: 'onVideo',
  1344. editable: 'onEditableArea'
  1345. }
  1346. };
  1347. /******************************************************************************/
  1348. vAPI.contextMenu.displayMenuItem = function({target}) {
  1349. var doc = target.ownerDocument;
  1350. var gContextMenu = doc.defaultView.gContextMenu;
  1351. if ( !gContextMenu.browser ) {
  1352. return;
  1353. }
  1354. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1355. var currentURI = gContextMenu.browser.currentURI;
  1356. // https://github.com/gorhill/uBlock/issues/105
  1357. // TODO: Should the element picker works on any kind of pages?
  1358. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1359. menuitem.hidden = true;
  1360. return;
  1361. }
  1362. var ctx = vAPI.contextMenu.contexts;
  1363. if ( !ctx ) {
  1364. menuitem.hidden = false;
  1365. return;
  1366. }
  1367. var ctxMap = vAPI.contextMenu.contextMap;
  1368. for ( var context of ctx ) {
  1369. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  1370. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  1371. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  1372. menuitem.hidden = false;
  1373. return;
  1374. }
  1375. if ( gContextMenu[ctxMap[context]] ) {
  1376. menuitem.hidden = false;
  1377. return;
  1378. }
  1379. }
  1380. menuitem.hidden = true;
  1381. };
  1382. /******************************************************************************/
  1383. vAPI.contextMenu.register = function(doc) {
  1384. if ( !this.menuItemId ) {
  1385. return;
  1386. }
  1387. if ( vAPI.fennec ) {
  1388. // TODO https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/API/NativeWindow/contextmenus/add
  1389. /*var nativeWindow = doc.defaultView.NativeWindow;
  1390. contextId = nativeWindow.contextmenus.add(
  1391. this.menuLabel,
  1392. nativeWindow.contextmenus.linkOpenableContext,
  1393. this.onCommand
  1394. );*/
  1395. return;
  1396. }
  1397. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1398. var menuitem = doc.createElement('menuitem');
  1399. menuitem.setAttribute('id', this.menuItemId);
  1400. menuitem.setAttribute('label', this.menuLabel);
  1401. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  1402. menuitem.setAttribute('class', 'menuitem-iconic');
  1403. menuitem.addEventListener('command', this.onCommand);
  1404. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1405. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1406. };
  1407. /******************************************************************************/
  1408. vAPI.contextMenu.unregister = function(doc) {
  1409. if ( !this.menuItemId ) {
  1410. return;
  1411. }
  1412. if ( vAPI.fennec ) {
  1413. // TODO
  1414. return;
  1415. }
  1416. var menuitem = doc.getElementById(this.menuItemId);
  1417. var contextMenu = menuitem.parentNode;
  1418. menuitem.removeEventListener('command', this.onCommand);
  1419. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1420. contextMenu.removeChild(menuitem);
  1421. };
  1422. /******************************************************************************/
  1423. vAPI.contextMenu.create = function(details, callback) {
  1424. this.menuItemId = details.id;
  1425. this.menuLabel = details.title;
  1426. this.contexts = details.contexts;
  1427. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1428. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1429. } else {
  1430. // default in Chrome
  1431. this.contexts = ['page'];
  1432. }
  1433. this.onCommand = function() {
  1434. var gContextMenu = getOwnerWindow(this).gContextMenu;
  1435. var details = {
  1436. menuItemId: this.id
  1437. };
  1438. if ( gContextMenu.inFrame ) {
  1439. details.tagName = 'iframe';
  1440. // Probably won't work with e10s
  1441. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1442. } else if ( gContextMenu.onImage ) {
  1443. details.tagName = 'img';
  1444. details.srcUrl = gContextMenu.mediaURL;
  1445. } else if ( gContextMenu.onAudio ) {
  1446. details.tagName = 'audio';
  1447. details.srcUrl = gContextMenu.mediaURL;
  1448. } else if ( gContextMenu.onVideo ) {
  1449. details.tagName = 'video';
  1450. details.srcUrl = gContextMenu.mediaURL;
  1451. } else if ( gContextMenu.onLink ) {
  1452. details.tagName = 'a';
  1453. details.linkUrl = gContextMenu.linkURL;
  1454. }
  1455. callback(details, {
  1456. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1457. url: gContextMenu.browser.currentURI.asciiSpec
  1458. });
  1459. };
  1460. for ( var win of vAPI.tabs.getWindows() ) {
  1461. this.register(win.document);
  1462. }
  1463. };
  1464. /******************************************************************************/
  1465. vAPI.lastError = function() {
  1466. return null;
  1467. };
  1468. /******************************************************************************/
  1469. // This is called only once, when everything has been loaded in memory after
  1470. // the extension was launched. It can be used to inject content scripts
  1471. // in already opened web pages, to remove whatever nuisance could make it to
  1472. // the web pages before uBlock was ready.
  1473. vAPI.onLoadAllCompleted = function() {};
  1474. /******************************************************************************/
  1475. // Likelihood is that we do not have to punycode: given punycode overhead,
  1476. // it's faster to check and skip than do it unconditionally all the time.
  1477. var punycodeHostname = punycode.toASCII;
  1478. var isNotASCII = /[^\x21-\x7F]/;
  1479. vAPI.punycodeHostname = function(hostname) {
  1480. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1481. };
  1482. vAPI.punycodeURL = function(url) {
  1483. if ( isNotASCII.test(url) ) {
  1484. return Services.io.newURI(url, null, null).asciiSpec;
  1485. }
  1486. return url;
  1487. };
  1488. /******************************************************************************/
  1489. vAPI.optionsObserver = {
  1490. register: function () {
  1491. var obs = Components.classes['@mozilla.org/observer-service;1'].getService(Components.interfaces.nsIObserverService);
  1492. obs.addObserver(this, "addon-options-displayed", false);
  1493. cleanupTasks.push(this.unregister.bind(this));
  1494. },
  1495. observe: function (aSubject, aTopic, aData) {
  1496. if (aTopic === "addon-options-displayed" && aData === "{2b10c1c8-a11f-4bad-fe9c-1c11e82cac42}") {
  1497. var doc = aSubject;
  1498. this.setupOptionsButton(doc, "showDashboardButton", "dashboard.html");
  1499. this.setupOptionsButton(doc, "showNetworkLogButton", "devtools.html");
  1500. }
  1501. },
  1502. setupOptionsButton: function (doc, id, page) {
  1503. var button = doc.getElementById(id);
  1504. button.addEventListener("command", function () {
  1505. vAPI.tabs.open({ url: page, index: -1 });
  1506. });
  1507. button.label = vAPI.i18n(id);
  1508. },
  1509. unregister: function () {
  1510. var obs = Components.classes['@mozilla.org/observer-service;1'].getService(Components.interfaces.nsIObserverService);
  1511. obs.removeObserver(this, "addon-options-displayed");
  1512. },
  1513. };
  1514. vAPI.optionsObserver.register();
  1515. /******************************************************************************/
  1516. // clean up when the extension is disabled
  1517. window.addEventListener('unload', function() {
  1518. for ( var cleanup of cleanupTasks ) {
  1519. cleanup();
  1520. }
  1521. // frameModule needs to be cleared too
  1522. var frameModule = {};
  1523. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  1524. frameModule.contentObserver.unregister();
  1525. Cu.unload(vAPI.getURL('frameModule.js'));
  1526. });
  1527. /******************************************************************************/
  1528. })();
  1529. /******************************************************************************/