embed.js 1.6 KB

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