content-hooks-frames-web.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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, Event */
  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 = (type, listener, options) => window.addEventListener(type, listener, options);
  48. const dispatchEvent = event => window.dispatchEvent(event);
  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 && ((...args) => console.warn(...args))) || (() => { });
  58. const observers = new Map();
  59. const observedElements = new Map();
  60. addEventListener(LOAD_DEFERRED_IMAGES_START_EVENT, () => loadDeferredImagesStart());
  61. addEventListener(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(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(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(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. const minHeight = document.documentElement.style.getPropertyValue("min-height");
  142. const minHeightPriority = document.documentElement.style.getPropertyPriority("min-height");
  143. document.documentElement.style.setProperty("transform-origin", (zoomFactorX < 1 ? "50%" : "0") + " " + (zoomFactorY < 1 ? "50%" : "0") + " 0", "important");
  144. document.documentElement.style.setProperty("transform", "scale3d(" + zoomFactor + ", " + zoomFactor + ", 1)", "important");
  145. document.documentElement.style.setProperty("min-height", (100 / zoomFactor) + "vh", "important");
  146. dispatchResizeEvent();
  147. if (keepZoomLevel) {
  148. document.documentElement.style.setProperty("-sf-transform", transform, transformPriority);
  149. document.documentElement.style.setProperty("-sf-transform-origin", transformOrigin, transformOriginPriority);
  150. document.documentElement.style.setProperty("-sf-min-height", minHeight, minHeightPriority);
  151. } else {
  152. document.documentElement.style.setProperty("transform", transform, transformPriority);
  153. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  154. document.documentElement.style.setProperty("min-height", minHeight, minHeightPriority);
  155. }
  156. }
  157. if (!keepZoomLevel) {
  158. dispatchResizeEvent();
  159. const docBoundingRect = scrollingElement.getBoundingClientRect();
  160. [...observers].forEach(([intersectionObserver, observer]) => {
  161. const rootBoundingRect = observer.options && observer.options.root && observer.options.root.getBoundingClientRect();
  162. const targetElements = observedElements.get(intersectionObserver);
  163. if (targetElements) {
  164. observer.callback(targetElements.map(target => {
  165. const boundingClientRect = target.getBoundingClientRect();
  166. const isIntersecting = true;
  167. const intersectionRatio = 1;
  168. const rootBounds = observer.options && observer.options.root ? rootBoundingRect : docBoundingRect;
  169. const time = 0;
  170. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  171. }), intersectionObserver);
  172. }
  173. });
  174. }
  175. }
  176. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => loadDeferredImagesEnd());
  177. addEventListener(LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_END_EVENT, () => loadDeferredImagesEnd(true));
  178. addEventListener(LOAD_DEFERRED_IMAGES_RESET_ZOOM_LEVEL_END_EVENT, () => {
  179. const transform = document.documentElement.style.getPropertyValue("-sf-transform");
  180. const transformPriority = document.documentElement.style.getPropertyPriority("-sf-transform");
  181. const transformOrigin = document.documentElement.style.getPropertyValue("-sf-transform-origin");
  182. const transformOriginPriority = document.documentElement.style.getPropertyPriority("-sf-transform-origin");
  183. const minHeight = document.documentElement.style.getPropertyValue("-sf-min-height");
  184. const minHeightPriority = document.documentElement.style.getPropertyPriority("-sf-min-height");
  185. document.documentElement.style.setProperty("transform", transform, transformPriority);
  186. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  187. document.documentElement.style.setProperty("min-height", minHeight, minHeightPriority);
  188. document.documentElement.style.removeProperty("-sf-transform");
  189. document.documentElement.style.removeProperty("-sf-transform-origin");
  190. document.documentElement.style.removeProperty("-sf-min-height");
  191. });
  192. function loadDeferredImagesEnd(keepZoomLevel) {
  193. const scrollingElement = document.scrollingElement || document.documentElement;
  194. document.querySelectorAll("[" + LAZY_LOAD_ATTRIBUTE + "]").forEach(element => {
  195. element.loading = "lazy";
  196. element.removeAttribute(LAZY_LOAD_ATTRIBUTE);
  197. });
  198. if (!keepZoomLevel) {
  199. delete scrollingElement.clientHeight;
  200. delete scrollingElement.clientWidth;
  201. delete screen.height;
  202. delete screen.width;
  203. if (window._singleFile_getBoundingClientRect) {
  204. Element.prototype.getBoundingClientRect = window._singleFile_getBoundingClientRect;
  205. window.innerHeight = window._singleFile_innerHeight;
  206. window.innerWidth = window._singleFile_innerWidth;
  207. delete window._singleFile_getBoundingClientRect;
  208. delete window._singleFile_innerHeight;
  209. delete window._singleFile_innerWidth;
  210. }
  211. }
  212. if (window._singleFileImage) {
  213. delete window.Image;
  214. window.Image = window._singleFileImage;
  215. delete window._singleFileImage;
  216. }
  217. if (!keepZoomLevel) {
  218. dispatchResizeEvent();
  219. }
  220. }
  221. addEventListener(BLOCK_COOKIES_START_EVENT, () => {
  222. try {
  223. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  224. } catch (error) {
  225. // ignored
  226. }
  227. });
  228. addEventListener(BLOCK_COOKIES_END_EVENT, () => {
  229. delete document.cookie;
  230. });
  231. addEventListener(BLOCK_STORAGE_START_EVENT, () => {
  232. if (!window._singleFile_localStorage) {
  233. window._singleFile_localStorage = window.localStorage;
  234. window.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  235. }
  236. if (!window._singleFile_indexedDB) {
  237. window._singleFile_indexedDB = window.indexedDB;
  238. window.__defineGetter__("indexedDB", () => { throw new Error("indexedDB temporary blocked by SingleFile"); });
  239. }
  240. });
  241. addEventListener(BLOCK_STORAGE_END_EVENT, () => {
  242. if (window._singleFile_localStorage) {
  243. delete window.localStorage;
  244. window.localStorage = window._singleFile_localStorage;
  245. delete window._singleFile_localStorage;
  246. }
  247. if (!window._singleFile_indexedDB) {
  248. delete window.indexedDB;
  249. window.indexedDB = window._singleFile_indexedDB;
  250. delete window._singleFile_indexedDB;
  251. }
  252. });
  253. if (window.FontFace) {
  254. const FontFace = window.FontFace;
  255. let warningFontFaceDisplayed;
  256. window.FontFace = function () {
  257. if (!warningFontFaceDisplayed) {
  258. warn("SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  259. warningFontFaceDisplayed = true;
  260. }
  261. const detail = {};
  262. detail["font-family"] = arguments[0];
  263. detail.src = arguments[1];
  264. const descriptors = arguments[2];
  265. if (descriptors) {
  266. Object.keys(descriptors).forEach(descriptor => {
  267. if (FONT_STYLE_PROPERTIES[descriptor]) {
  268. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  269. }
  270. });
  271. }
  272. if (detail.src instanceof ArrayBuffer) {
  273. const reader = new FileReader();
  274. reader.readAsDataURL(new Blob([detail.src]));
  275. reader.addEventListener("load", () => {
  276. detail.src = "url(" + reader.result + ")";
  277. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  278. });
  279. } else {
  280. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  281. }
  282. return new FontFace(...arguments);
  283. };
  284. window.FontFace.toString = function () { return "function FontFace() { [native code] }"; };
  285. }
  286. if (window.IntersectionObserver) {
  287. const IntersectionObserver = window.IntersectionObserver;
  288. let warningIntersectionObserverDisplayed;
  289. window.IntersectionObserver = function () {
  290. if (!warningIntersectionObserverDisplayed) {
  291. warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  292. warningIntersectionObserverDisplayed = true;
  293. }
  294. const intersectionObserver = new IntersectionObserver(...arguments);
  295. const observeIntersection = IntersectionObserver.prototype.observe || intersectionObserver.observe;
  296. const unobserveIntersection = IntersectionObserver.prototype.unobserve || intersectionObserver.unobserve;
  297. const callback = arguments[0];
  298. const options = arguments[1];
  299. if (observeIntersection) {
  300. intersectionObserver.observe = function (targetElement) {
  301. let targetElements = observedElements.get(intersectionObserver);
  302. if (!targetElements) {
  303. targetElements = [];
  304. observedElements.set(intersectionObserver, targetElements);
  305. }
  306. targetElements.push(targetElement);
  307. return observeIntersection.call(intersectionObserver, targetElement);
  308. };
  309. }
  310. if (unobserveIntersection) {
  311. intersectionObserver.unobserve = function (targetElement) {
  312. let targetElements = observedElements.get(intersectionObserver);
  313. if (targetElements) {
  314. targetElements = targetElements.filter(element => element != targetElement);
  315. if (targetElements.length) {
  316. observedElements.set(intersectionObserver, targetElements);
  317. } else {
  318. observedElements.delete(intersectionObserver);
  319. observers.delete(intersectionObserver);
  320. }
  321. }
  322. return unobserveIntersection.call(intersectionObserver, targetElement);
  323. };
  324. }
  325. observers.set(intersectionObserver, { callback, options });
  326. return intersectionObserver;
  327. };
  328. window.IntersectionObserver.prototype = IntersectionObserver.prototype;
  329. window.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code] }"; };
  330. }
  331. function dispatchResizeEvent() {
  332. try {
  333. dispatchEvent(new UIEvent("resize"));
  334. document.dispatchEvent(new Event("scroll", { bubbles: true }));
  335. } catch (error) {
  336. // ignored
  337. }
  338. }
  339. })();