hooks-frame.js 14 KB

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