1
0

embed.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // @ts-check
  2. (function () {
  3. 'use strict';
  4. /**
  5. * @param {() => void} loaded
  6. */
  7. var ready = function (loaded) {
  8. if (document.readyState === 'complete') {
  9. loaded();
  10. } else {
  11. document.addEventListener('readystatechange', function () {
  12. if (document.readyState === 'complete') {
  13. loaded();
  14. }
  15. });
  16. }
  17. };
  18. ready(function () {
  19. /** @type {Map<number, HTMLIFrameElement>} */
  20. var iframes = new Map();
  21. window.addEventListener('message', function (e) {
  22. var data = e.data || {};
  23. if (typeof data !== 'object' || data.type !== 'setHeight' || !iframes.has(data.id)) {
  24. return;
  25. }
  26. var iframe = iframes.get(data.id);
  27. if ('source' in e && iframe.contentWindow !== e.source) {
  28. return;
  29. }
  30. iframe.height = data.height;
  31. });
  32. [].forEach.call(document.querySelectorAll('iframe.mastodon-embed'), function (iframe) {
  33. // select unique id for each iframe
  34. var id = 0, failCount = 0, idBuffer = new Uint32Array(1);
  35. while (id === 0 || iframes.has(id)) {
  36. id = crypto.getRandomValues(idBuffer)[0];
  37. failCount++;
  38. if (failCount > 100) {
  39. // give up and assign (easily guessable) unique number if getRandomValues is broken or no luck
  40. id = -(iframes.size + 1);
  41. break;
  42. }
  43. }
  44. iframes.set(id, iframe);
  45. iframe.scrolling = 'no';
  46. iframe.style.overflow = 'hidden';
  47. iframe.onload = function () {
  48. iframe.contentWindow.postMessage({
  49. type: 'setHeight',
  50. id: id,
  51. }, '*');
  52. };
  53. iframe.onload();
  54. });
  55. });
  56. })();