hooks-frame.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. /*
  2. * Copyright 2010-2019 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, FileReader, Blob, setTimeout, clearTimeout, screen, Element, UIEvent */
  21. this.hooksFrame = this.hooksFrame || (() => {
  22. const LOAD_DEFERRED_IMAGES_START_EVENT = "single-file-load-deferred-images-start";
  23. const LOAD_DEFERRED_IMAGES_END_EVENT = "single-file-load-deferred-images-end";
  24. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  25. const fontFaces = [];
  26. if (document instanceof HTMLDocument) {
  27. const scriptElement = document.createElement("script");
  28. scriptElement.textContent = `(${hook.toString()})()`;
  29. (document.documentElement || document).appendChild(scriptElement);
  30. scriptElement.remove();
  31. addEventListener(NEW_FONT_FACE_EVENT, event => fontFaces.push(event.detail));
  32. }
  33. return {
  34. getFontsData: () => fontFaces,
  35. loadDeferredImagesStart: () => dispatchEvent(new CustomEvent(LOAD_DEFERRED_IMAGES_START_EVENT)),
  36. loadDeferredImagesEnd: () => dispatchEvent(new CustomEvent(LOAD_DEFERRED_IMAGES_END_EVENT))
  37. };
  38. function hook() {
  39. const LOAD_DEFERRED_IMAGES_START_EVENT = "single-file-load-deferred-images-start";
  40. const LOAD_DEFERRED_IMAGES_END_EVENT = "single-file-load-deferred-images-end";
  41. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  42. const FONT_STYLE_PROPERTIES = {
  43. family: "font-family",
  44. style: "font-style",
  45. weight: "font-weight",
  46. stretch: "font-stretch",
  47. unicodeRange: "unicode-range",
  48. variant: "font-variant",
  49. featureSettings: "font-feature-settings"
  50. };
  51. const requestAnimationFrame = window.requestAnimationFrame;
  52. const cancelAnimationFrame = window.cancelAnimationFrame;
  53. const observers = new Map();
  54. const observedElements = new Map();
  55. let loadDeferredImages;
  56. addEventListener(LOAD_DEFERRED_IMAGES_START_EVENT, () => {
  57. loadDeferredImages = true;
  58. const clientHeight = document.documentElement.clientHeight;
  59. const clientWidth = document.documentElement.clientWidth;
  60. const scrollHeight = Math.max(document.documentElement.scrollHeight - (clientHeight * .5), clientHeight);
  61. const scrollWidth = Math.max(document.documentElement.scrollWidth - (clientWidth * .5), clientWidth);
  62. window._singleFile_innerHeight = window.innerHeight;
  63. window._singleFile_innerWidth = window.innerWidth;
  64. window.__defineGetter__("innerHeight", () => scrollHeight);
  65. window.__defineGetter__("innerWidth", () => scrollWidth);
  66. document.documentElement.__defineGetter__("clientHeight", () => scrollHeight);
  67. document.documentElement.__defineGetter__("clientWidth", () => scrollWidth);
  68. screen.__defineGetter__("height", () => scrollHeight);
  69. screen.__defineGetter__("width", () => scrollWidth);
  70. window._singleFile_getBoundingClientRect = Element.prototype.getBoundingClientRect;
  71. Element.prototype.getBoundingClientRect = function () {
  72. const boundingRect = window._singleFile_getBoundingClientRect.call(this);
  73. if (this == document.documentElement) {
  74. boundingRect.__defineGetter__("height", () => scrollHeight);
  75. boundingRect.__defineGetter__("bottom", () => scrollHeight + boundingRect.top);
  76. boundingRect.__defineGetter__("width", () => scrollWidth);
  77. boundingRect.__defineGetter__("right", () => scrollWidth + boundingRect.left);
  78. }
  79. return boundingRect;
  80. };
  81. window._singleFile_localStorage = window.localStorage;
  82. window.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  83. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  84. dispatchEvent(new UIEvent("resize"));
  85. dispatchEvent(new UIEvent("scroll"));
  86. const docBoundingRect = document.documentElement.getBoundingClientRect();
  87. Array.from(observers).forEach(([intersectionObserver, observer]) => {
  88. const rootBoundingRect = observer.options.root && observer.options.root.getBoundingClientRect();
  89. observer.callback(observedElements.get(intersectionObserver).map(target => {
  90. const boundingClientRect = target.getBoundingClientRect();
  91. const isIntersecting = true;
  92. const intersectionRatio = 1;
  93. const rootBounds = observer.options && observer.options.root ? rootBoundingRect : docBoundingRect;
  94. const time = 0;
  95. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  96. }), intersectionObserver);
  97. });
  98. if (pendingRequestAnimationFrameCalls.size) {
  99. Array.from(pendingRequestAnimationFrameCalls).forEach(([id, callback]) => {
  100. pendingRequestAnimationFrameCalls.delete(id);
  101. cancelAnimationFrame(id);
  102. callback();
  103. });
  104. }
  105. });
  106. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => {
  107. loadDeferredImages = false;
  108. delete document.documentElement.clientHeight;
  109. delete document.documentElement.clientWidth;
  110. delete screen.height;
  111. delete screen.width;
  112. if (window._singleFile_getBoundingClientRect) {
  113. Element.prototype.getBoundingClientRect = window._singleFile_getBoundingClientRect;
  114. window.innerHeight = window._singleFile_innerHeight;
  115. window.innerWidth = window._singleFile_innerWidth;
  116. delete window._singleFile_getBoundingClientRect;
  117. delete window._singleFile_innerHeight;
  118. delete window._singleFile_innerWidth;
  119. delete document.cookie;
  120. delete window.localStorage;
  121. window.localStorage = window._singleFile_localStorage;
  122. delete window._singleFile_localStorage;
  123. }
  124. dispatchEvent(new UIEvent("resize"));
  125. dispatchEvent(new UIEvent("scroll"));
  126. });
  127. let warningRequestAnimationFrameDisplayed;
  128. const pendingRequestAnimationFrameCalls = new Map();
  129. window.requestAnimationFrame = function (callback) {
  130. if (!warningRequestAnimationFrameDisplayed) {
  131. console.warn("SingleFile is hooking the requestAnimationFrame function to load deferred images."); // eslint-disable-line no-console
  132. warningRequestAnimationFrameDisplayed = true;
  133. }
  134. if (loadDeferredImages) {
  135. return setTimeout(callback, 0);
  136. } else {
  137. const id = requestAnimationFrame(timestamp => {
  138. pendingRequestAnimationFrameCalls.delete(id);
  139. callback(timestamp);
  140. });
  141. pendingRequestAnimationFrameCalls.set(id, callback);
  142. return id;
  143. }
  144. };
  145. window.requestAnimationFrame.toString = function () { return "requestAnimationFrame() { [native code] }"; };
  146. window.cancelAnimationFrame = function (id) {
  147. pendingRequestAnimationFrameCalls.delete(id);
  148. if (loadDeferredImages) {
  149. return clearTimeout(id);
  150. } else {
  151. return cancelAnimationFrame(id);
  152. }
  153. };
  154. window.cancelAnimationFrame.toString = function () { return "cancelAnimationFrame() { [native code] }"; };
  155. const FontFace = window.FontFace;
  156. let warningFontFaceDisplayed;
  157. window.__defineGetter__("FontFace", () => new Proxy(FontFace, {
  158. construct(FontFace, argumentsList) {
  159. if (!warningFontFaceDisplayed) {
  160. console.warn("SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  161. warningFontFaceDisplayed = true;
  162. }
  163. const detail = {};
  164. detail["font-family"] = argumentsList[0];
  165. detail.src = argumentsList[1];
  166. const descriptors = argumentsList[2];
  167. if (descriptors) {
  168. Object.keys(descriptors).forEach(descriptor => {
  169. if (FONT_STYLE_PROPERTIES[descriptor]) {
  170. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  171. }
  172. });
  173. }
  174. if (detail.src instanceof ArrayBuffer) {
  175. const reader = new FileReader();
  176. reader.readAsDataURL(new Blob([detail.src]));
  177. reader.addEventListener("load", () => {
  178. detail.src = "url(" + reader.result + ")";
  179. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  180. });
  181. } else {
  182. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  183. }
  184. return new FontFace(...argumentsList);
  185. }
  186. }));
  187. if (window.IntersectionObserver) {
  188. const IntersectionObserver = window.IntersectionObserver;
  189. const observeIntersection = IntersectionObserver.prototype.observe;
  190. const unobserveIntersection = IntersectionObserver.prototype.unobserve;
  191. let warningIntersectionObserverDisplayed;
  192. window.__defineGetter__("IntersectionObserver", () => new Proxy(IntersectionObserver, {
  193. construct(IntersectionObserver, argumentsList) {
  194. if (!warningIntersectionObserverDisplayed) {
  195. console.warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  196. warningRequestAnimationFrameDisplayed = true;
  197. }
  198. const intersectionObserver = new IntersectionObserver(...argumentsList);
  199. const callback = argumentsList[0];
  200. const options = argumentsList[1];
  201. intersectionObserver.observe = function (targetElement) {
  202. let targetElements = observedElements.get(intersectionObserver);
  203. if (!targetElements) {
  204. targetElements = [];
  205. observedElements.set(intersectionObserver, targetElements);
  206. }
  207. targetElements.push(targetElement);
  208. return observeIntersection.call(intersectionObserver, targetElement);
  209. };
  210. intersectionObserver.unobserve = function (targetElement) {
  211. let targetElements = observedElements.get(intersectionObserver);
  212. if (targetElements) {
  213. targetElements = targetElements.filter(element => element <= targetElement);
  214. if (targetElements.length) {
  215. observedElements.set(intersectionObserver, targetElements);
  216. } else {
  217. observedElements.delete(intersectionObserver);
  218. }
  219. }
  220. return unobserveIntersection.call(intersectionObserver, targetElement);
  221. };
  222. observers.set(intersectionObserver, { callback, options });
  223. return intersectionObserver;
  224. }
  225. }));
  226. window.__defineSetter__("IntersectionObserver", () => { });
  227. }
  228. }
  229. })();