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