embed.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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(!iframe) return;
  28. if ('source' in e && iframe.contentWindow !== e.source) {
  29. return;
  30. }
  31. iframe.height = data.height;
  32. });
  33. document.querySelectorAll('iframe.mastodon-embed').forEach(iframe => {
  34. // select unique id for each iframe
  35. var id = 0, failCount = 0, idBuffer = new Uint32Array(1);
  36. while (id === 0 || iframes.has(id)) {
  37. id = crypto.getRandomValues(idBuffer)[0];
  38. failCount++;
  39. if (failCount > 100) {
  40. // give up and assign (easily guessable) unique number if getRandomValues is broken or no luck
  41. id = -(iframes.size + 1);
  42. break;
  43. }
  44. }
  45. iframes.set(id, iframe);
  46. iframe.scrolling = 'no';
  47. iframe.style.overflow = 'hidden';
  48. iframe.onload = function () {
  49. iframe.contentWindow.postMessage({
  50. type: 'setHeight',
  51. id: id,
  52. }, '*');
  53. };
  54. iframe.onload();
  55. });
  56. });
  57. })();