font-face-proxy.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global window, addEventListener, dispatchEvent, CustomEvent, document, HTMLDocument */
  21. this.fontFaceProxy = this.fontFaceProxy || (() => {
  22. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  23. const fontFaces = [];
  24. if (document instanceof HTMLDocument) {
  25. const scriptElement = document.createElement("script");
  26. scriptElement.textContent = `(${hook.toString()})()`;
  27. document.documentElement.appendChild(scriptElement);
  28. scriptElement.remove();
  29. addEventListener(NEW_FONT_FACE_EVENT, event => fontFaces.push(event.detail));
  30. }
  31. return {
  32. getFontsData: () => fontFaces
  33. };
  34. function hook() {
  35. const FONT_STYLE_PROPERTIES = {
  36. family: "font-family",
  37. style: "font-style",
  38. weight: "font-weight",
  39. stretch: "font-stretch",
  40. unicodeRange: "unicode-range",
  41. variant: "font-variant",
  42. featureSettings: "font-feature-settings"
  43. };
  44. const FontFace = window.FontFace;
  45. window.__defineGetter__("FontFace", () => new Proxy(FontFace, {
  46. construct(FontFace, argumentsList) {
  47. console.warn("SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  48. const detail = {};
  49. detail["font-family"] = argumentsList[0];
  50. detail.src = argumentsList[1];
  51. const descriptors = argumentsList[2];
  52. if (descriptors) {
  53. Object.keys(descriptors).forEach(descriptor => detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor]);
  54. }
  55. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  56. return new FontFace(...argumentsList);
  57. }
  58. }));
  59. }
  60. })();