How to automatically adjust iframe height for embedded wordpress posts

Ugh, I got it to work. The problem was that I was using a custom class on the iframe tag and Discourse strips all those tags. I should have learned my lesson from a few days ago (Formatting posts to look more like Wordpress blog - #6 by jimkleiber). I’ve read that it’s a security reason for why custom HTML classes don’t work here but I’m not sure why :confused:

However, here’s the code for adjusting the height of an iframe with the .topic-body iframe selector (not sure if this code works for others, seems to work for me):

<script type="text/discourse-plugin" version="0.8.18">
    api.decorateCookedElement(
      element => {
        setTimeout(function() {
          let iframes = element.querySelectorAll('.topic-body iframe');
          if (iframes) {
            iframes.forEach(function(iframe) {
              iframe.onload = function() {
                let iframeDocument = this.contentDocument || this.contentWindow.document;
                let contentHeight = Math.max(
                  iframeDocument.body.scrollHeight,
                  iframeDocument.documentElement.scrollHeight
                ) + 'px';
                this.style.height = contentHeight;
              };
            });
          }
        }, 5000); // Adjust the delay as needed                  
      },
      { id: "component-id", onlyStream: true}
    );
</script>

EDIT: actually, it doesn’t work. I added height="4000px" in the iframe tag and that’s why it was working, I think.

1 Like