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.

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