content-hooks-frames-web.js 15 KB

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