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.

1618 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
  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. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  626. this.callback = this.proxy.bind(this); // bind once
  627. this.init(messageManager, channelName, listenerId, requestId);
  628. };
  629. CallbackWrapper.junkyard = [];
  630. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  631. var wrapper = CallbackWrapper.junkyard.pop();
  632. if ( wrapper ) {
  633. wrapper.init(messageManager, channelName, listenerId, requestId);
  634. return wrapper;
  635. }
  636. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  637. };
  638. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  639. this.messageManager = messageManager;
  640. this.channelName = channelName;
  641. this.listenerId = listenerId;
  642. this.requestId = requestId;
  643. };
  644. CallbackWrapper.prototype.proxy = function(response) {
  645. var message = JSON.stringify({
  646. requestId: this.requestId,
  647. channelName: this.channelName,
  648. msg: response !== undefined ? response : null
  649. });
  650. if ( this.messageManager.sendAsyncMessage ) {
  651. this.messageManager.sendAsyncMessage(this.listenerId, message);
  652. } else {
  653. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  654. }
  655. // Mark for reuse
  656. this.messageManager =
  657. this.channelName =
  658. this.requestId =
  659. this.listenerId = null;
  660. CallbackWrapper.junkyard.push(this);
  661. };
  662. /******************************************************************************/
  663. var httpObserver = {
  664. classDescription: 'net-channel-event-sinks for ' + location.host,
  665. classID: Components.ID('{dc8d6319-5f6e-4438-999e-53722db99e84}'),
  666. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  667. ABORT: Components.results.NS_BINDING_ABORTED,
  668. ACCEPT: Components.results.NS_SUCCEEDED,
  669. // Request types: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  670. MAIN_FRAME: Ci.nsIContentPolicy.TYPE_DOCUMENT,
  671. VALID_CSP_TARGETS: 1 << Ci.nsIContentPolicy.TYPE_DOCUMENT |
  672. 1 << Ci.nsIContentPolicy.TYPE_SUBDOCUMENT,
  673. typeMap: {
  674. 1: 'other',
  675. 2: 'script',
  676. 3: 'image',
  677. 4: 'stylesheet',
  678. 5: 'object',
  679. 6: 'main_frame',
  680. 7: 'sub_frame',
  681. 11: 'xmlhttprequest',
  682. 12: 'object',
  683. 14: 'font'
  684. },
  685. lastRequest: {
  686. url: null,
  687. type: null,
  688. tabId: null,
  689. frameId: null,
  690. parentFrameId: null,
  691. openerURL: null
  692. },
  693. get componentRegistrar() {
  694. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  695. },
  696. get categoryManager() {
  697. return Cc['@mozilla.org/categorymanager;1']
  698. .getService(Ci.nsICategoryManager);
  699. },
  700. QueryInterface: (function() {
  701. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  702. return XPCOMUtils.generateQI([
  703. Ci.nsIFactory,
  704. Ci.nsIObserver,
  705. Ci.nsIChannelEventSink,
  706. Ci.nsISupportsWeakReference
  707. ]);
  708. })(),
  709. createInstance: function(outer, iid) {
  710. if ( outer ) {
  711. throw Components.results.NS_ERROR_NO_AGGREGATION;
  712. }
  713. return this.QueryInterface(iid);
  714. },
  715. register: function() {
  716. Services.obs.addObserver(this, 'http-on-opening-request', true);
  717. Services.obs.addObserver(this, 'http-on-examine-response', true);
  718. this.componentRegistrar.registerFactory(
  719. this.classID,
  720. this.classDescription,
  721. this.contractID,
  722. this
  723. );
  724. this.categoryManager.addCategoryEntry(
  725. 'net-channel-event-sinks',
  726. this.contractID,
  727. this.contractID,
  728. false,
  729. true
  730. );
  731. },
  732. unregister: function() {
  733. Services.obs.removeObserver(this, 'http-on-opening-request');
  734. Services.obs.removeObserver(this, 'http-on-examine-response');
  735. this.componentRegistrar.unregisterFactory(this.classID, this);
  736. this.categoryManager.deleteCategoryEntry(
  737. 'net-channel-event-sinks',
  738. this.contractID,
  739. false
  740. );
  741. },
  742. handlePopup: function(URI, tabId, sourceTabId) {
  743. if ( !sourceTabId ) {
  744. return false;
  745. }
  746. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  747. return false;
  748. }
  749. var result = vAPI.tabs.onPopup({
  750. tabId: tabId,
  751. sourceTabId: sourceTabId,
  752. url: URI.asciiSpec
  753. });
  754. return result === true;
  755. },
  756. handleRequest: function(channel, URI, details) {
  757. var onBeforeRequest = vAPI.net.onBeforeRequest;
  758. var type = this.typeMap[details.type] || 'other';
  759. if ( onBeforeRequest.types.has(type) === false ) {
  760. return false;
  761. }
  762. var result = onBeforeRequest.callback({
  763. frameId: details.frameId,
  764. hostname: URI.asciiHost,
  765. parentFrameId: details.parentFrameId,
  766. tabId: details.tabId,
  767. type: type,
  768. url: URI.asciiSpec
  769. });
  770. if ( !result || typeof result !== 'object' ) {
  771. return false;
  772. }
  773. if ( result.cancel === true ) {
  774. channel.cancel(this.ABORT);
  775. return true;
  776. }
  777. if ( result.redirectUrl ) {
  778. channel.redirectionLimit = 1;
  779. channel.redirectTo(
  780. Services.io.newURI(result.redirectUrl, null, null)
  781. );
  782. return true;
  783. }
  784. return false;
  785. },
  786. observe: function(channel, topic) {
  787. if ( !(channel instanceof Ci.nsIHttpChannel) ) {
  788. return;
  789. }
  790. var URI = channel.URI;
  791. var channelData, result;
  792. if ( topic === 'http-on-examine-response' ) {
  793. if ( !(channel instanceof Ci.nsIWritablePropertyBag) ) {
  794. return;
  795. }
  796. try {
  797. /*[
  798. type,
  799. tabId,
  800. sourceTabId - given if it was a popup,
  801. frameId,
  802. parentFrameId
  803. ]*/
  804. channelData = channel.getProperty(location.host + 'reqdata');
  805. } catch (ex) {
  806. return;
  807. }
  808. if ( !channelData ) {
  809. return;
  810. }
  811. if ( (1 << channelData[0] & this.VALID_CSP_TARGETS) === 0 ) {
  812. return;
  813. }
  814. topic = 'Content-Security-Policy';
  815. try {
  816. result = channel.getResponseHeader(topic);
  817. } catch (ex) {
  818. result = null;
  819. }
  820. result = vAPI.net.onHeadersReceived.callback({
  821. hostname: URI.asciiHost,
  822. parentFrameId: channelData[4],
  823. responseHeaders: result ? [{name: topic, value: result}] : [],
  824. tabId: channelData[1],
  825. url: URI.asciiSpec
  826. });
  827. if ( result ) {
  828. channel.setResponseHeader(
  829. topic,
  830. result.responseHeaders.pop().value,
  831. true
  832. );
  833. }
  834. return;
  835. }
  836. // http-on-opening-request
  837. var lastRequest = this.lastRequest;
  838. if ( lastRequest.url === null ) {
  839. this.handleRequest(channel, URI, {tabId: vAPI.noTabId, type: 1});
  840. return;
  841. }
  842. // Important! When loading file via XHR for mirroring,
  843. // the URL will be the same, so it could fall into an infinite loop
  844. lastRequest.url = null;
  845. var sourceTabId = null;
  846. // Popup candidate (only for main_frame type)
  847. if ( lastRequest.openerURL ) {
  848. for ( var tab of vAPI.tabs.getAll() ) {
  849. var tabURI = tab.linkedBrowser.currentURI;
  850. // Probably isn't the best method to identify the source tab
  851. if ( tabURI.spec !== lastRequest.openerURL ) {
  852. continue;
  853. }
  854. sourceTabId = vAPI.tabs.getTabId(tab);
  855. if ( sourceTabId !== lastRequest.tabId ) {
  856. break;
  857. }
  858. sourceTabId = null;
  859. }
  860. if ( this.handlePopup(channel.URI, lastRequest.tabId, sourceTabId) ) {
  861. channel.cancel(this.ABORT);
  862. return;
  863. }
  864. }
  865. if ( this.handleRequest(channel, URI, lastRequest) ) {
  866. return;
  867. }
  868. // If request is not handled we may use the data in on-modify-request
  869. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  870. channel.setProperty(
  871. location.host + 'reqdata',
  872. [
  873. lastRequest.type,
  874. lastRequest.tabId,
  875. sourceTabId,
  876. lastRequest.frameId,
  877. lastRequest.parentFrameId
  878. ]
  879. );
  880. }
  881. },
  882. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  883. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  884. var result = this.ACCEPT;
  885. // If error thrown, the redirect will fail
  886. try {
  887. // skip internal redirects?
  888. /*if ( flags & 4 ) {
  889. console.log('internal redirect skipped');
  890. return;
  891. }*/
  892. var URI = newChannel.URI;
  893. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  894. return;
  895. }
  896. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  897. return;
  898. }
  899. // TODO: what if a behind-the-scene request is being redirected?
  900. // This data is present only for tabbed requests, so if this throws,
  901. // the redirection won't be evaluated and canceled (if necessary)
  902. var channelData = oldChannel.getProperty(location.host + 'reqdata');
  903. if ( this.handlePopup(URI, channelData[1], channelData[2]) ) {
  904. result = this.ABORT;
  905. return;
  906. }
  907. var details = {
  908. type: channelData[0],
  909. tabId: channelData[1],
  910. frameId: channelData[3],
  911. parentFrameId: channelData[4]
  912. };
  913. if ( this.handleRequest(newChannel, URI, details) ) {
  914. result = this.ABORT;
  915. return;
  916. }
  917. // Carry the data on in case of multiple redirects
  918. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  919. newChannel.setProperty(location.host + 'reqdata', channelData);
  920. }
  921. } catch (ex) {
  922. // console.error(ex);
  923. } finally {
  924. callback.onRedirectVerifyCallback(result);
  925. }
  926. }
  927. };
  928. /******************************************************************************/
  929. vAPI.net = {};
  930. /******************************************************************************/
  931. vAPI.net.registerListeners = function() {
  932. // Since it's not used
  933. this.onBeforeSendHeaders = null;
  934. this.onBeforeRequest.types = new Set(this.onBeforeRequest.types);
  935. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  936. var shouldLoadListener = function(e) {
  937. var details = e.data;
  938. var lastRequest = httpObserver.lastRequest;
  939. lastRequest.url = details.url;
  940. lastRequest.type = details.type;
  941. lastRequest.tabId = vAPI.tabs.getTabId(e.target);
  942. lastRequest.frameId = details.frameId;
  943. lastRequest.parentFrameId = details.parentFrameId;
  944. lastRequest.openerURL = details.openerURL;
  945. };
  946. vAPI.messaging.globalMessageManager.addMessageListener(
  947. shouldLoadListenerMessageName,
  948. shouldLoadListener
  949. );
  950. httpObserver.register();
  951. cleanupTasks.push(function() {
  952. vAPI.messaging.globalMessageManager.removeMessageListener(
  953. shouldLoadListenerMessageName,
  954. shouldLoadListener
  955. );
  956. httpObserver.unregister();
  957. });
  958. };
  959. /******************************************************************************/
  960. vAPI.toolbarButton = {
  961. id: location.host + '-button',
  962. type: 'view',
  963. viewId: location.host + '-panel',
  964. label: vAPI.app.name,
  965. tooltiptext: vAPI.app.name,
  966. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  967. };
  968. /******************************************************************************/
  969. vAPI.toolbarButton.init = function() {
  970. try {
  971. var {CustomizableUI} = Cu.import('resource:///modules/CustomizableUI.jsm', null);
  972. } catch (ex) {
  973. return;
  974. }
  975. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  976. this.styleURI = [
  977. '#' + this.id + ' {',
  978. 'list-style-image: url(',
  979. vAPI.getURL('img/browsericons/icon16-off.svg'),
  980. ');',
  981. '}',
  982. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  983. 'width: 160px;',
  984. 'height: 290px;',
  985. 'overflow: hidden !important;',
  986. '}'
  987. ];
  988. var platformVersion = Services.appinfo.platformVersion;
  989. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  990. this.styleURI.push(
  991. '#' + this.id + '[badge]:not([badge=""])::after {',
  992. 'position: absolute;',
  993. 'margin-left: -16px;',
  994. 'margin-top: 3px;',
  995. 'padding: 1px 2px;',
  996. 'font-size: 9px;',
  997. 'font-weight: bold;',
  998. 'color: #fff;',
  999. 'background: #666;',
  1000. 'content: attr(badge);',
  1001. '}'
  1002. );
  1003. }
  1004. this.styleURI = Services.io.newURI(
  1005. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  1006. null,
  1007. null
  1008. );
  1009. this.closePopup = function({target}) {
  1010. CustomizableUI.hidePanelForNode(
  1011. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  1012. );
  1013. };
  1014. CustomizableUI.createWidget(this);
  1015. vAPI.messaging.globalMessageManager.addMessageListener(
  1016. location.host + ':closePopup',
  1017. this.closePopup
  1018. );
  1019. cleanupTasks.push(function() {
  1020. CustomizableUI.destroyWidget(this.id);
  1021. vAPI.messaging.globalMessageManager.removeMessageListener(
  1022. location.host + ':closePopup',
  1023. this.closePopup
  1024. );
  1025. for ( var win of vAPI.tabs.getWindows() ) {
  1026. var panel = win.document.getElementById(this.viewId);
  1027. panel.parentNode.removeChild(panel);
  1028. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1029. .getInterface(Ci.nsIDOMWindowUtils)
  1030. .removeSheet(this.styleURI, 1);
  1031. }
  1032. }.bind(this));
  1033. };
  1034. /******************************************************************************/
  1035. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  1036. var panel = doc.createElement('panelview');
  1037. panel.setAttribute('id', this.viewId);
  1038. var iframe = doc.createElement('iframe');
  1039. iframe.setAttribute('type', 'content');
  1040. doc.getElementById('PanelUI-multiView')
  1041. .appendChild(panel)
  1042. .appendChild(iframe);
  1043. var updateTimer = null;
  1044. var delayedResize = function() {
  1045. if ( updateTimer ) {
  1046. return;
  1047. }
  1048. updateTimer = setTimeout(resizePopup, 20);
  1049. };
  1050. var resizePopup = function() {
  1051. var body = iframe.contentDocument.body;
  1052. panel.parentNode.style.maxWidth = 'none';
  1053. // Set the hegiht first, then the width for proper resising
  1054. panel.style.height = iframe.style.height = body.clientHeight + 'px';
  1055. panel.style.width = iframe.style.width = body.clientWidth + 'px';
  1056. updateTimer = null;
  1057. };
  1058. var onPopupReady = function() {
  1059. var win = this.contentWindow;
  1060. if ( !win || win.location.host !== location.host ) {
  1061. return;
  1062. }
  1063. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1064. attributes: true,
  1065. characterData: true,
  1066. subtree: true
  1067. });
  1068. delayedResize();
  1069. };
  1070. iframe.addEventListener('load', onPopupReady, true);
  1071. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1072. .getInterface(Ci.nsIDOMWindowUtils)
  1073. .loadSheet(this.styleURI, 1);
  1074. };
  1075. /******************************************************************************/
  1076. vAPI.toolbarButton.onCreated = function(button) {
  1077. var platformVersion = Services.appinfo.platformVersion;
  1078. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1079. return;
  1080. }
  1081. button.setAttribute('badge', '');
  1082. button.classList.add('badged-button');
  1083. setTimeout(function() {
  1084. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1085. button,
  1086. 'class',
  1087. 'toolbarbutton-badge'
  1088. );
  1089. if ( !badge ) {
  1090. return;
  1091. }
  1092. badge.style.cssText = [
  1093. 'position: absolute;',
  1094. 'bottom: 0;',
  1095. 'right: 0;',
  1096. 'padding: 1px;',
  1097. 'background: #666;',
  1098. 'color: #fff;',
  1099. 'font-size: 9px;',
  1100. 'font-weight: bold;'
  1101. ].join('');
  1102. }, 1000);
  1103. };
  1104. /******************************************************************************/
  1105. vAPI.toolbarButton.onViewShowing = function({target}) {
  1106. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1107. };
  1108. /******************************************************************************/
  1109. vAPI.toolbarButton.onViewHiding = function({target}) {
  1110. target.parentNode.style.maxWidth = '';
  1111. target.firstChild.setAttribute('src', 'about:blank');
  1112. };
  1113. /******************************************************************************/
  1114. vAPI.toolbarButton.init();
  1115. /******************************************************************************/
  1116. vAPI.contextMenu = {
  1117. contextMap: {
  1118. frame: 'inFrame',
  1119. link: 'onLink',
  1120. image: 'onImage',
  1121. audio: 'onAudio',
  1122. video: 'onVideo',
  1123. editable: 'onEditableArea'
  1124. }
  1125. };
  1126. /******************************************************************************/
  1127. vAPI.contextMenu.displayMenuItem = function(e) {
  1128. var doc = e.target.ownerDocument;
  1129. var gContextMenu = doc.defaultView.gContextMenu;
  1130. if ( !gContextMenu.browser ) {
  1131. return;
  1132. }
  1133. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1134. var currentURI = gContextMenu.browser.currentURI;
  1135. // https://github.com/gorhill/uBlock/issues/105
  1136. // TODO: Should the element picker works on any kind of pages?
  1137. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1138. menuitem.hidden = true;
  1139. return;
  1140. }
  1141. var ctx = vAPI.contextMenu.contexts;
  1142. if ( !ctx ) {
  1143. menuitem.hidden = false;
  1144. return;
  1145. }
  1146. var ctxMap = vAPI.contextMenu.contextMap;
  1147. for ( var context of ctx ) {
  1148. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  1149. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  1150. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  1151. menuitem.hidden = false;
  1152. return;
  1153. }
  1154. if ( gContextMenu[ctxMap[context]] ) {
  1155. menuitem.hidden = false;
  1156. return;
  1157. }
  1158. }
  1159. menuitem.hidden = true;
  1160. };
  1161. /******************************************************************************/
  1162. vAPI.contextMenu.register = function(doc) {
  1163. if ( !this.menuItemId ) {
  1164. return;
  1165. }
  1166. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1167. var menuitem = doc.createElement('menuitem');
  1168. menuitem.setAttribute('id', this.menuItemId);
  1169. menuitem.setAttribute('label', this.menuLabel);
  1170. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  1171. menuitem.setAttribute('class', 'menuitem-iconic');
  1172. menuitem.addEventListener('command', this.onCommand);
  1173. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1174. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1175. };
  1176. /******************************************************************************/
  1177. vAPI.contextMenu.unregister = function(doc) {
  1178. if ( !this.menuItemId ) {
  1179. return;
  1180. }
  1181. var menuitem = doc.getElementById(this.menuItemId);
  1182. var contextMenu = menuitem.parentNode;
  1183. menuitem.removeEventListener('command', this.onCommand);
  1184. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1185. contextMenu.removeChild(menuitem);
  1186. };
  1187. /******************************************************************************/
  1188. vAPI.contextMenu.create = function(details, callback) {
  1189. this.menuItemId = details.id;
  1190. this.menuLabel = details.title;
  1191. this.contexts = details.contexts;
  1192. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1193. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1194. } else {
  1195. // default in Chrome
  1196. this.contexts = ['page'];
  1197. }
  1198. this.onCommand = function() {
  1199. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  1200. var details = {
  1201. menuItemId: this.id
  1202. };
  1203. if ( gContextMenu.inFrame ) {
  1204. details.tagName = 'iframe';
  1205. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1206. } else if ( gContextMenu.onImage ) {
  1207. details.tagName = 'img';
  1208. details.srcUrl = gContextMenu.mediaURL;
  1209. } else if ( gContextMenu.onAudio ) {
  1210. details.tagName = 'audio';
  1211. details.srcUrl = gContextMenu.mediaURL;
  1212. } else if ( gContextMenu.onVideo ) {
  1213. details.tagName = 'video';
  1214. details.srcUrl = gContextMenu.mediaURL;
  1215. } else if ( gContextMenu.onLink ) {
  1216. details.tagName = 'a';
  1217. details.linkUrl = gContextMenu.linkURL;
  1218. }
  1219. callback(details, {
  1220. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1221. url: gContextMenu.browser.currentURI.asciiSpec
  1222. });
  1223. };
  1224. for ( var win of vAPI.tabs.getWindows() ) {
  1225. this.register(win.document);
  1226. }
  1227. };
  1228. /******************************************************************************/
  1229. vAPI.contextMenu.remove = function() {
  1230. for ( var win of vAPI.tabs.getWindows() ) {
  1231. this.unregister(win.document);
  1232. }
  1233. this.menuItemId = null;
  1234. this.menuLabel = null;
  1235. this.contexts = null;
  1236. this.onCommand = null;
  1237. };
  1238. /******************************************************************************/
  1239. vAPI.lastError = function() {
  1240. return null;
  1241. };
  1242. /******************************************************************************/
  1243. // This is called only once, when everything has been loaded in memory after
  1244. // the extension was launched. It can be used to inject content scripts
  1245. // in already opened web pages, to remove whatever nuisance could make it to
  1246. // the web pages before uBlock was ready.
  1247. vAPI.onLoadAllCompleted = function() {};
  1248. /******************************************************************************/
  1249. // Likelihood is that we do not have to punycode: given punycode overhead,
  1250. // it's faster to check and skip than do it unconditionally all the time.
  1251. var punycodeHostname = punycode.toASCII;
  1252. var isNotASCII = /[^\x21-\x7F]/;
  1253. vAPI.punycodeHostname = function(hostname) {
  1254. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1255. };
  1256. vAPI.punycodeURL = function(url) {
  1257. if ( isNotASCII.test(url) ) {
  1258. return Services.io.newURI(url, null, null).asciiSpec;
  1259. }
  1260. return url;
  1261. };
  1262. /******************************************************************************/
  1263. // clean up when the extension is disabled
  1264. window.addEventListener('unload', function() {
  1265. for ( var cleanup of cleanupTasks ) {
  1266. cleanup();
  1267. }
  1268. // frameModule needs to be cleared too
  1269. var frameModule = {};
  1270. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  1271. frameModule.contentObserver.unregister();
  1272. Cu.unload(vAPI.getURL('frameModule.js'));
  1273. });
  1274. /******************************************************************************/
  1275. })();
  1276. /******************************************************************************/