hooks-frame.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 window, addEventListener, dispatchEvent, CustomEvent, document, HTMLDocument, FileReader, Blob, screen, Element, UIEvent */
  24. this.hooksFrame = this.hooksFrame || (() => {
  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. const scriptElement = document.createElement("script");
  33. scriptElement.textContent = `(${hook.toString()})(${JSON.stringify({ LOAD_DEFERRED_IMAGES_START_EVENT, LOAD_DEFERRED_IMAGES_END_EVENT, LOAD_IMAGE_EVENT, IMAGE_LOADED_EVENT, NEW_FONT_FACE_EVENT })})`;
  34. (document.documentElement || document).appendChild(scriptElement);
  35. scriptElement.remove();
  36. addEventListener(NEW_FONT_FACE_EVENT, event => fontFaces.push(event.detail));
  37. }
  38. return {
  39. getFontsData: () => fontFaces,
  40. loadDeferredImagesStart: () => dispatchEvent(new CustomEvent(LOAD_DEFERRED_IMAGES_START_EVENT)),
  41. loadDeferredImagesEnd: () => dispatchEvent(new CustomEvent(LOAD_DEFERRED_IMAGES_END_EVENT)),
  42. LOAD_IMAGE_EVENT,
  43. IMAGE_LOADED_EVENT
  44. };
  45. function hook(constants) {
  46. const {
  47. LOAD_DEFERRED_IMAGES_START_EVENT,
  48. LOAD_DEFERRED_IMAGES_END_EVENT,
  49. LOAD_IMAGE_EVENT,
  50. IMAGE_LOADED_EVENT,
  51. NEW_FONT_FACE_EVENT
  52. } = constants;
  53. const FONT_STYLE_PROPERTIES = {
  54. family: "font-family",
  55. style: "font-style",
  56. weight: "font-weight",
  57. stretch: "font-stretch",
  58. unicodeRange: "unicode-range",
  59. variant: "font-variant",
  60. featureSettings: "font-feature-settings"
  61. };
  62. const requestAnimationFrame = window.requestAnimationFrame;
  63. const cancelAnimationFrame = window.cancelAnimationFrame;
  64. const observers = new Map();
  65. const observedElements = new Map();
  66. let loadDeferredImages;
  67. addEventListener(LOAD_DEFERRED_IMAGES_START_EVENT, () => {
  68. loadDeferredImages = true;
  69. const clientHeight = document.documentElement.clientHeight;
  70. const clientWidth = document.documentElement.clientWidth;
  71. const scrollHeight = Math.max(document.documentElement.scrollHeight - (clientHeight * .5), clientHeight);
  72. const scrollWidth = Math.max(document.documentElement.scrollWidth - (clientWidth * .5), clientWidth);
  73. document.documentElement.__defineGetter__("clientHeight", () => scrollHeight);
  74. document.documentElement.__defineGetter__("clientWidth", () => scrollWidth);
  75. screen.__defineGetter__("height", () => scrollHeight);
  76. screen.__defineGetter__("width", () => scrollWidth);
  77. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  78. if (!window._singleFile_getBoundingClientRect) {
  79. window._singleFile_getBoundingClientRect = Element.prototype.getBoundingClientRect;
  80. Element.prototype.getBoundingClientRect = function () {
  81. const boundingRect = window._singleFile_getBoundingClientRect.call(this);
  82. if (this == document.documentElement) {
  83. boundingRect.__defineGetter__("height", () => scrollHeight);
  84. boundingRect.__defineGetter__("bottom", () => scrollHeight + boundingRect.top);
  85. boundingRect.__defineGetter__("width", () => scrollWidth);
  86. boundingRect.__defineGetter__("right", () => scrollWidth + boundingRect.left);
  87. }
  88. return boundingRect;
  89. };
  90. window._singleFile_innerHeight = window.innerHeight;
  91. window._singleFile_innerWidth = window.innerWidth;
  92. window.__defineGetter__("innerHeight", () => scrollHeight);
  93. window.__defineGetter__("innerWidth", () => scrollWidth);
  94. }
  95. if (!window._singleFile_localStorage) {
  96. window._singleFile_localStorage = window.localStorage;
  97. window.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  98. }
  99. if (!window._singleFile_indexedDB) {
  100. window._singleFile_indexedDB = window.indexedDB;
  101. window.__defineGetter__("indexedDB", () => { throw new Error("indexedDB temporary blocked by SingleFile"); });
  102. }
  103. if (!window._singleFileImage) {
  104. const Image = window.Image;
  105. window._singleFileImage = window.Image;
  106. window.__defineGetter__("Image", function () {
  107. return function () {
  108. const image = new Image(...arguments);
  109. const result = new Image(...arguments);
  110. result.__defineSetter__("src", function (value) {
  111. image.src = value;
  112. dispatchEvent(new CustomEvent(LOAD_IMAGE_EVENT, { detail: image.src }));
  113. });
  114. result.__defineGetter__("src", function () {
  115. return image.src;
  116. });
  117. result.__defineSetter__("srcset", function (value) {
  118. dispatchEvent(new CustomEvent(LOAD_IMAGE_EVENT));
  119. image.srcset = value;
  120. });
  121. result.__defineGetter__("srcset", function () {
  122. return image.srcset;
  123. });
  124. image.onload = image.onloadend = image.onerror = event => {
  125. dispatchEvent(new CustomEvent(IMAGE_LOADED_EVENT, { detail: image.src }));
  126. result.dispatchEvent(new UIEvent(event.type, event));
  127. };
  128. return result;
  129. };
  130. });
  131. }
  132. const zoomFactorX = (clientHeight + window.scrollY) / scrollHeight;
  133. const zoomFactorY = (clientWidth + window.scrollX) / scrollWidth;
  134. const zoomFactor = Math.min(zoomFactorX, zoomFactorY);
  135. if (zoomFactor < 1) {
  136. const transform = document.documentElement.style.getPropertyValue("transform");
  137. const transformPriority = document.documentElement.style.getPropertyPriority("transform");
  138. const transformOrigin = document.documentElement.style.getPropertyValue("transform-origin");
  139. const transformOriginPriority = document.documentElement.style.getPropertyPriority("transform-origin");
  140. document.documentElement.style.setProperty("transform-origin", (zoomFactorX < 1 ? "50%" : "0") + " " + (zoomFactorY < 1 ? "50%" : "0") + " 0", "important");
  141. document.documentElement.style.setProperty("transform", "scale3d(" + zoomFactor + ", " + zoomFactor + ", 1)", "important");
  142. dispatchEvent(new UIEvent("resize"));
  143. dispatchEvent(new UIEvent("scroll"));
  144. document.documentElement.style.setProperty("transform", transform, transformPriority);
  145. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  146. }
  147. dispatchEvent(new UIEvent("resize"));
  148. dispatchEvent(new UIEvent("scroll"));
  149. const docBoundingRect = document.documentElement.getBoundingClientRect();
  150. Array.from(observers).forEach(([intersectionObserver, observer]) => {
  151. const rootBoundingRect = observer.options.root && observer.options.root.getBoundingClientRect();
  152. observer.callback(observedElements.get(intersectionObserver).map(target => {
  153. const boundingClientRect = target.getBoundingClientRect();
  154. const isIntersecting = true;
  155. const intersectionRatio = 1;
  156. const rootBounds = observer.options && observer.options.root ? rootBoundingRect : docBoundingRect;
  157. const time = 0;
  158. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  159. }), intersectionObserver);
  160. });
  161. if (pendingRequestAnimationFrameCalls.size) {
  162. Array.from(pendingRequestAnimationFrameCalls).forEach(([id, callback]) => {
  163. cancelAnimationFrame(id);
  164. callback();
  165. });
  166. }
  167. });
  168. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => {
  169. loadDeferredImages = false;
  170. delete document.documentElement.clientHeight;
  171. delete document.documentElement.clientWidth;
  172. delete screen.height;
  173. delete screen.width;
  174. delete document.cookie;
  175. if (window._singleFile_getBoundingClientRect) {
  176. Element.prototype.getBoundingClientRect = window._singleFile_getBoundingClientRect;
  177. window.innerHeight = window._singleFile_innerHeight;
  178. window.innerWidth = window._singleFile_innerWidth;
  179. delete window._singleFile_getBoundingClientRect;
  180. delete window._singleFile_innerHeight;
  181. delete window._singleFile_innerWidth;
  182. }
  183. if (window._singleFile_localStorage) {
  184. delete window.localStorage;
  185. window.localStorage = window._singleFile_localStorage;
  186. delete window._singleFile_localStorage;
  187. }
  188. if (!window._singleFile_indexedDB) {
  189. delete window.indexedDB;
  190. window.indexedDB = window._singleFile_indexedDB;
  191. delete window._singleFile_indexedDB;
  192. }
  193. if (window._singleFileImage) {
  194. delete window.Image;
  195. window.Image = window._singleFileImage;
  196. delete window._singleFileImage;
  197. }
  198. dispatchEvent(new UIEvent("resize"));
  199. dispatchEvent(new UIEvent("scroll"));
  200. });
  201. let warningRequestAnimationFrameDisplayed;
  202. const pendingRequestAnimationFrameCalls = new Map();
  203. let lastTimestamp = 0;
  204. window.requestAnimationFrame = function (callback) {
  205. if (!warningRequestAnimationFrameDisplayed) {
  206. console.warn("SingleFile is hooking the requestAnimationFrame and cancelAnimationFrame functions to load deferred images."); // eslint-disable-line no-console
  207. warningRequestAnimationFrameDisplayed = true;
  208. }
  209. let requestId;
  210. if (loadDeferredImages) {
  211. requestId = 0;
  212. callback(lastTimestamp);
  213. } else {
  214. requestId = requestAnimationFrame(timestamp => {
  215. pendingRequestAnimationFrameCalls.delete(requestId);
  216. lastTimestamp = timestamp;
  217. callback(timestamp);
  218. });
  219. pendingRequestAnimationFrameCalls.set(requestId, callback);
  220. }
  221. return requestId;
  222. };
  223. window.requestAnimationFrame.toString = function () { return "requestAnimationFrame() { [native code] }"; };
  224. window.cancelAnimationFrame = function (requestId) {
  225. pendingRequestAnimationFrameCalls.delete(requestId);
  226. return cancelAnimationFrame(requestId);
  227. };
  228. window.cancelAnimationFrame.toString = function () { return "cancelAnimationFrame() { [native code] }"; };
  229. if (window.FontFace) {
  230. const FontFace = window.FontFace;
  231. let warningFontFaceDisplayed;
  232. window.FontFace = function () {
  233. if (!warningFontFaceDisplayed) {
  234. console.warn("SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  235. warningFontFaceDisplayed = true;
  236. }
  237. const detail = {};
  238. detail["font-family"] = arguments[0];
  239. detail.src = arguments[1];
  240. const descriptors = arguments[2];
  241. if (descriptors) {
  242. Object.keys(descriptors).forEach(descriptor => {
  243. if (FONT_STYLE_PROPERTIES[descriptor]) {
  244. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  245. }
  246. });
  247. }
  248. if (detail.src instanceof ArrayBuffer) {
  249. const reader = new FileReader();
  250. reader.readAsDataURL(new Blob([detail.src]));
  251. reader.addEventListener("load", () => {
  252. detail.src = "url(" + reader.result + ")";
  253. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  254. });
  255. } else {
  256. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  257. }
  258. return new FontFace(...arguments);
  259. };
  260. window.FontFace.toString = function () { return "function FontFace() { [native code]"; };
  261. }
  262. if (window.IntersectionObserver) {
  263. const IntersectionObserver = window.IntersectionObserver;
  264. const observeIntersection = IntersectionObserver.prototype.observe;
  265. const unobserveIntersection = IntersectionObserver.prototype.unobserve;
  266. let warningIntersectionObserverDisplayed;
  267. window.IntersectionObserver = function () {
  268. if (!warningIntersectionObserverDisplayed) {
  269. console.warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  270. warningIntersectionObserverDisplayed = true;
  271. }
  272. const intersectionObserver = new IntersectionObserver(...arguments);
  273. const callback = arguments[0];
  274. const options = arguments[1];
  275. intersectionObserver.observe = function (targetElement) {
  276. let targetElements = observedElements.get(intersectionObserver);
  277. if (!targetElements) {
  278. targetElements = [];
  279. observedElements.set(intersectionObserver, targetElements);
  280. }
  281. targetElements.push(targetElement);
  282. return observeIntersection.call(intersectionObserver, targetElement);
  283. };
  284. intersectionObserver.unobserve = function (targetElement) {
  285. let targetElements = observedElements.get(intersectionObserver);
  286. if (targetElements) {
  287. targetElements = targetElements.filter(element => element <= targetElement);
  288. if (targetElements.length) {
  289. observedElements.set(intersectionObserver, targetElements);
  290. } else {
  291. observedElements.delete(intersectionObserver);
  292. }
  293. }
  294. return unobserveIntersection.call(intersectionObserver, targetElement);
  295. };
  296. observers.set(intersectionObserver, { callback, options });
  297. return intersectionObserver;
  298. };
  299. window.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code]"; };
  300. }
  301. }
  302. })();