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.

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