font-face-proxy.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 fontFaces = [];
  23. if (document instanceof HTMLDocument) {
  24. const scriptElement = document.createElement("script");
  25. scriptElement.textContent = `(${hook.toString()})()`;
  26. document.documentElement.appendChild(scriptElement);
  27. scriptElement.remove();
  28. addEventListener("single-file-font-face", event => fontFaces.push(event.detail));
  29. }
  30. return {
  31. getFontsData: () => fontFaces
  32. };
  33. function hook() {
  34. const FONT_STYLE_PROPERTIES = {
  35. family: "font-family",
  36. style: "font-style",
  37. weight: "font-weight",
  38. stretch: "font-stretch",
  39. unicodeRange: "unicode-range",
  40. variant: "font-variant",
  41. featureSettings: "font-feature-settings"
  42. };
  43. const FontFace = window.FontFace;
  44. window.__defineGetter__("FontFace", () => new Proxy(FontFace, {
  45. construct(FontFace, argumentsList) {
  46. console.warn("SingleFile is hooking The FontFace constructor to get font URLs."); // eslint-disable-line no-console
  47. const detail = {};
  48. detail["font-family"] = argumentsList[0];
  49. detail.src = argumentsList[1];
  50. const descriptors = argumentsList[2];
  51. if (descriptors) {
  52. Object.keys(descriptors).forEach(descriptor => detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor]);
  53. }
  54. dispatchEvent(new CustomEvent("single-file-font-face", { detail }));
  55. return new FontFace(...argumentsList);
  56. }
  57. }));
  58. }
  59. })();