Adjust width and height of iframe to fit with content in it

前端 未结 30 2771
旧时难觅i
旧时难觅i 2020-11-22 02:09

I need a solution for auto-adjusting the width and height of an iframe to barely fit its content. The point is that t

30条回答
  •  天涯浪人
    2020-11-22 02:41

    Context

    I had to do this myself in a context of a web-extension. This web-extension injects some piece of UI into each page, and this UI lives inside an iframe. The content inside the iframe is dynamic, so I had to readjust the width and height of the iframe itself.

    I use React but the concept applies to every library.

    My solution (this assumes that you control both the page and the iframe)

    Inside the iframe I changed body styles to have really big dimensions. This will allow the elements inside to lay out using all the necessary space. Making width and height 100% didn't work for me (I guess because the iframe has a default width = 300px and height = 150px)

    /* something like this */
    body {
      width: 99999px;
      height: 99999px;
    }
    

    Then I injected all the iframe UI inside a div and gave it some styles

    #ui-root {
      display: 'inline-block';     
    }
    

    After rendering my app inside this #ui-root (in React I do this inside componentDidMount) I compute the dimensions of this div like and sync them to the parent page using window.postMessage:

    let elRect = el.getBoundingClientRect()
    window.parent.postMessage({
      type: 'resize-iframe',
      payload: {
        width: elRect.width,
        height: elRect.height
      }
    }, '*')
    

    In the parent frame I do something like this:

    window.addEventListener('message', (ev) => {
      if(ev.data.type && ev.data.type === 'resize-iframe') {
        iframe.style.width = ev.data.payload.width + 'px'
        iframe.style.height = ev.data.payload.height + 'px'
      }
    }, false)
    

提交回复
热议问题