content-hooks-frame.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global browser, window, addEventListener, dispatchEvent, CustomEvent, document, HTMLDocument, FileReader, Blob */
  24. this.singlefile.lib.hooks.content.frame = this.singlefile.lib.hooks.content.frame || (() => {
  25. const LOAD_DEFERRED_IMAGES_START_EVENT = "single-file-load-deferred-images-start";
  26. const LOAD_DEFERRED_IMAGES_END_EVENT = "single-file-load-deferred-images-end";
  27. const LOAD_IMAGE_EVENT = "single-file-load-image";
  28. const IMAGE_LOADED_EVENT = "single-file-image-loaded";
  29. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  30. const fontFaces = [];
  31. if (document instanceof HTMLDocument) {
  32. let scriptElement = document.createElement("script");
  33. if (typeof browser !== "undefined" && browser.runtime && browser.runtime.getURL) {
  34. scriptElement.src = browser.runtime.getURL("/lib/hooks/content/content-hooks-web.js");
  35. } else if (this.singlefile.lib.getFileContent) {
  36. scriptElement.textContent = this.singlefile.lib.getFileContent("/lib/hooks/content/content-hooks-web.js");
  37. }
  38. (document.documentElement || document).appendChild(scriptElement);
  39. scriptElement.remove();
  40. scriptElement = document.createElement("script");
  41. scriptElement.textContent = `(${hook.toString()})(${JSON.stringify({ LOAD_DEFERRED_IMAGES_START_EVENT, LOAD_DEFERRED_IMAGES_END_EVENT, NEW_FONT_FACE_EVENT })})`;
  42. (document.documentElement || document).appendChild(scriptElement);
  43. scriptElement.remove();
  44. addEventListener(NEW_FONT_FACE_EVENT, event => fontFaces.push(event.detail));
  45. }
  46. return {
  47. getFontsData: () => fontFaces,
  48. loadDeferredImagesStart: () => dispatchEvent(new CustomEvent(LOAD_DEFERRED_IMAGES_START_EVENT)),
  49. loadDeferredImagesEnd: () => dispatchEvent(new CustomEvent(LOAD_DEFERRED_IMAGES_END_EVENT)),
  50. LOAD_IMAGE_EVENT,
  51. IMAGE_LOADED_EVENT
  52. };
  53. function hook(constants) {
  54. const {
  55. LOAD_DEFERRED_IMAGES_START_EVENT,
  56. LOAD_DEFERRED_IMAGES_END_EVENT,
  57. NEW_FONT_FACE_EVENT
  58. } = constants;
  59. const FONT_STYLE_PROPERTIES = {
  60. family: "font-family",
  61. style: "font-style",
  62. weight: "font-weight",
  63. stretch: "font-stretch",
  64. unicodeRange: "unicode-range",
  65. variant: "font-variant",
  66. featureSettings: "font-feature-settings"
  67. };
  68. const requestAnimationFrame = window.requestAnimationFrame;
  69. const cancelAnimationFrame = window.cancelAnimationFrame;
  70. const observers = new Map();
  71. const observedElements = new Map();
  72. let loadDeferredImages;
  73. addEventListener(LOAD_DEFERRED_IMAGES_START_EVENT, () => {
  74. loadDeferredImages = true;
  75. const docBoundingRect = document.documentElement.getBoundingClientRect();
  76. Array.from(observers).forEach(([intersectionObserver, observer]) => {
  77. const rootBoundingRect = observer.options.root && observer.options.root.getBoundingClientRect();
  78. observer.callback(observedElements.get(intersectionObserver).map(target => {
  79. const boundingClientRect = target.getBoundingClientRect();
  80. const isIntersecting = true;
  81. const intersectionRatio = 1;
  82. const rootBounds = observer.options && observer.options.root ? rootBoundingRect : docBoundingRect;
  83. const time = 0;
  84. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  85. }), intersectionObserver);
  86. });
  87. if (pendingRequestAnimationFrameCalls.size) {
  88. Array.from(pendingRequestAnimationFrameCalls).forEach(([id, callback]) => {
  89. cancelAnimationFrame(id);
  90. callback();
  91. });
  92. }
  93. });
  94. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => {
  95. loadDeferredImages = false;
  96. });
  97. let warningRequestAnimationFrameDisplayed;
  98. const pendingRequestAnimationFrameCalls = new Map();
  99. let lastTimestamp = 0;
  100. let errorDetected;
  101. window.requestAnimationFrame = function (callback) {
  102. if (!warningRequestAnimationFrameDisplayed) {
  103. console.warn("SingleFile is hooking the requestAnimationFrame and cancelAnimationFrame functions to load deferred images."); // eslint-disable-line no-console
  104. warningRequestAnimationFrameDisplayed = true;
  105. }
  106. let requestId;
  107. if (loadDeferredImages && !errorDetected) {
  108. try {
  109. requestId = 0;
  110. callback(lastTimestamp);
  111. } catch (error) {
  112. errorDetected = true;
  113. requestId = requestAnimationFrame(timestamp => {
  114. lastTimestamp = timestamp;
  115. callback(timestamp);
  116. });
  117. }
  118. } else {
  119. if (!loadDeferredImages) {
  120. errorDetected = false;
  121. }
  122. requestId = requestAnimationFrame(timestamp => {
  123. pendingRequestAnimationFrameCalls.delete(requestId);
  124. lastTimestamp = timestamp;
  125. callback(timestamp);
  126. });
  127. pendingRequestAnimationFrameCalls.set(requestId, callback);
  128. }
  129. return requestId;
  130. };
  131. window.requestAnimationFrame.toString = function () { return "requestAnimationFrame() { [native code] }"; };
  132. window.cancelAnimationFrame = function (requestId) {
  133. pendingRequestAnimationFrameCalls.delete(requestId);
  134. return cancelAnimationFrame(requestId);
  135. };
  136. window.cancelAnimationFrame.toString = function () { return "cancelAnimationFrame() { [native code] }"; };
  137. if (window.FontFace) {
  138. const FontFace = window.FontFace;
  139. let warningFontFaceDisplayed;
  140. window.FontFace = function () {
  141. if (!warningFontFaceDisplayed) {
  142. console.warn("SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  143. warningFontFaceDisplayed = true;
  144. }
  145. const detail = {};
  146. detail["font-family"] = arguments[0];
  147. detail.src = arguments[1];
  148. const descriptors = arguments[2];
  149. if (descriptors) {
  150. Object.keys(descriptors).forEach(descriptor => {
  151. if (FONT_STYLE_PROPERTIES[descriptor]) {
  152. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  153. }
  154. });
  155. }
  156. if (detail.src instanceof ArrayBuffer) {
  157. const reader = new FileReader();
  158. reader.readAsDataURL(new Blob([detail.src]));
  159. reader.addEventListener("load", () => {
  160. detail.src = "url(" + reader.result + ")";
  161. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  162. });
  163. } else {
  164. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  165. }
  166. return new FontFace(...arguments);
  167. };
  168. window.FontFace.toString = function () { return "function FontFace() { [native code]"; };
  169. }
  170. if (window.IntersectionObserver) {
  171. const IntersectionObserver = window.IntersectionObserver;
  172. const observeIntersection = IntersectionObserver.prototype.observe;
  173. const unobserveIntersection = IntersectionObserver.prototype.unobserve;
  174. let warningIntersectionObserverDisplayed;
  175. window.IntersectionObserver = function () {
  176. if (!warningIntersectionObserverDisplayed) {
  177. console.warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  178. warningIntersectionObserverDisplayed = true;
  179. }
  180. const intersectionObserver = new IntersectionObserver(...arguments);
  181. const callback = arguments[0];
  182. const options = arguments[1];
  183. intersectionObserver.observe = function (targetElement) {
  184. let targetElements = observedElements.get(intersectionObserver);
  185. if (!targetElements) {
  186. targetElements = [];
  187. observedElements.set(intersectionObserver, targetElements);
  188. }
  189. targetElements.push(targetElement);
  190. return observeIntersection.call(intersectionObserver, targetElement);
  191. };
  192. intersectionObserver.unobserve = function (targetElement) {
  193. let targetElements = observedElements.get(intersectionObserver);
  194. if (targetElements) {
  195. targetElements = targetElements.filter(element => element <= targetElement);
  196. if (targetElements.length) {
  197. observedElements.set(intersectionObserver, targetElements);
  198. } else {
  199. observedElements.delete(intersectionObserver);
  200. }
  201. }
  202. return unobserveIntersection.call(intersectionObserver, targetElement);
  203. };
  204. observers.set(intersectionObserver, { callback, options });
  205. return intersectionObserver;
  206. };
  207. window.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code]"; };
  208. }
  209. }
  210. })();