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.

1845 lines
53 KiB

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