content-hooks-frames-web.js 14 KB

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