hooks-frame.js 14 KB

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