content-hooks-frames-web.js 14 KB

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