font-face-proxy.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /* global window, addEventListener, dispatchEvent, CustomEvent, document, HTMLDocument */
  2. this.fontFaceProxy = this.fontFaceProxy || (() => {
  3. const fontFaces = [];
  4. if (document instanceof HTMLDocument) {
  5. const scriptElement = document.createElement("script");
  6. scriptElement.textContent = `(${hook.toString()})()`;
  7. document.documentElement.appendChild(scriptElement);
  8. scriptElement.remove();
  9. addEventListener("single-file-font-face", event => fontFaces.push(event.detail));
  10. }
  11. return {
  12. getFontsData: () => fontFaces
  13. };
  14. function hook() {
  15. const FONT_STYLE_PROPERTIES = {
  16. family: "font-family",
  17. style: "font-style",
  18. weight: "font-weight",
  19. stretch: "font-stretch",
  20. unicodeRange: "unicode-range",
  21. variant: "font-variant",
  22. featureSettings: "font-feature-settings"
  23. };
  24. const FontFace = window.FontFace;
  25. window.__defineGetter__("FontFace", () => new Proxy(FontFace, {
  26. construct(FontFace, argumentsList) {
  27. const detail = {};
  28. detail["font-family"] = argumentsList[0];
  29. detail.src = argumentsList[1];
  30. const descriptors = argumentsList[2];
  31. if (descriptors) {
  32. Object.keys(descriptors).forEach(descriptor => {
  33. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  34. });
  35. }
  36. dispatchEvent(new CustomEvent("single-file-font-face", { detail }));
  37. return new FontFace(...argumentsList);
  38. }
  39. }));
  40. }
  41. })();