content-hooks-frames-web.js 14 KB

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