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.

1949 lines
56 KiB

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