Liveview resizing iFrames's heights to fit contents by obtaining the scrollHeight

Hi,

I need to resizing iFrames’s heights to fit contents by obtaining the scrollHeight. I created a JS Hook and used it in heex.

heex

<iframe 
  srcdoc={@email.body} 
  class="w-full" 
  id={"email-#{@email.id}"} 
  phx-hook="Iframe"
>
</iframe>

js hook

const Iframe = {
  mounted() {
    this.el.style.height = this.el.contentWindow.document.body.scrollHeight+25+'px';
  }
}

export default Iframe;

My problem is this code only work when I refresh the page.

  • When I click the page link, then come to the page, mounted() function run but not resize iframe height. It doesn’t work!
  • When I press “CTRL + R” and refresh the page, mounted() function also run then resize the iframe height. It works.

Any idea?

Thanks.