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.

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