Is there a cross-domain iframe height auto-resizer that works?

后端 未结 7 2418
暖寄归人
暖寄归人 2020-11-27 09:41

I tried a few solutions but wasn\'t successful. I\'m wondering if there is a solution out there preferably with an easy-to-follow tutorial.

7条回答
  •  感动是毒
    2020-11-27 10:16

    I ran into this issue while working on something at work (using React). Basically, we have some external html content that we save into our document table in the database and then insert onto the page under certain circumstances when you're in the Documents dataset.

    So, given n inlines, of which up to n could contain external html, we needed to devise a system to automatically resize the iframe of each inline once the content fully loaded in each. After spinning my wheels for a bit, this is how I ended up doing it:

    1. Set a message event listener in the index of our React app which checks for a a specific key that we will set from the sender iframe.
    2. In the component that actually renders the iframes, after inserting the external html into it, I append a ` ) } return html.join("\n") })()} onLoad={(event) => { // if the browser does not enforce a cross-origin policy, // then just access the height directly instead try { const { target } = event const contentDocument = ( target.contentDocument || // Earlier versions of IE or IE8+ where !DOCTYPE is not specified target.contentWindow.document ) if (contentDocument) { target.style.height = `${contentDocument.body.scrollHeight}px` } } catch (error) { const expectedError = ( `Blocked a frame with origin "${window.location.origin}" ` + `from accessing a cross-origin frame.` ) if (error.message !== expectedError) { /* eslint-disable no-console */ console.err( `An error (${error.message}) ocurred while trying to check to see ` + "if the inner iframe is accessible or not depending " + "on the browser cross-origin policy" ) } } }} />

提交回复
热议问题