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.

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