vue3+electron 动态插入 iframe 如何自适应高度?-灵析社区

大厂球袋

我在做一个需求,是需要从 electron 后台获取到 html 路径,之后动态创建 iframe 插入到编辑器 目前代码如下: ipcRenderer.on("h5-iframe", (event, arg) => { let iframe = document.createElement('iframe'); iframe.src = arg; iframe.width = '100%'; iframe.src = arg console.log(1, iframe.contentDocument) // 1 null console.log(2, iframe.document) // 2 undefined iframe.addEventListener('load', (event) => { console.log(3, iframe.contentDocument) console.log(4, iframe.document) }) iframe.onload = function () { console.log(5, iframe.contentDocument) console.log(6, iframe.document) } let div = document.createElement('div'); div.appendChild(iframe); let iframeHtml = div.innerHTML; tinymce .get(tinymceId.value) .execCommand( "mceInsertContent", false, iframeHtml ); }); 但得到的结果是如下,导致无法获取内容计算高度 `console.log(1, iframe.contentDocument)` 为 `null` `console.log(2, iframe.document)` 为 `undefined` `frame.addEventListener('load', (event) => {})` 和 `iframe.onload = function () {}` 均无任何反馈 已知 `arg` 可以正确返回, 且页面可以正常插入显示,所以应该也不是跨域问题 * * * 请问如何解决?万分感谢!

阅读量:155

点赞量:0

问AI
ipcRenderer.on("h5-iframe", (event, arg) => { const iframe = document.createElement('iframe'); iframe.src = arg; iframe.style.width = '100%'; const editorContent = document.getElementById('editor-content'); editorContent.appendChild(iframe); iframe.onload = function () { // 获取高度并调整 const height = iframe.contentWindow.document.body.scrollHeight; iframe.style.height = `${height}px`; }; }); 或者用 MutationObserver 监听 iframe 里面 DOM 变化: function adjustIframeHeight(iframe) { const height = iframe.contentWindow.document.body.scrollHeight; iframe.style.height = `${height}px`; } ipcRenderer.on("h5-iframe", (event, arg) => { const iframe = document.createElement('iframe'); iframe.src = arg; iframe.style.width = '100%'; const editorContent = document.getElementById('editor-content'); // 确保这个元素存在 editorContent.appendChild(iframe); iframe.onload = function () { adjustIframeHeight(iframe); const observer = new MutationObserver(() => adjustIframeHeight(iframe)); observer.observe(iframe.contentDocument.body, { childList: true, subtree: true }); }; });