将 javascript 注入并执行到 iframe

问题描述

我从 api 获取一串 HTML,我需要将它传递到我页面上的 iframe 中。这样做的同时,我还需要向 iframe 的头部和主体注入一些 javascript 代码

我已经能够通过以下方式成功地做到这一点。我在这里使用 React,但它不应该有什么不同...

return (
    <iframe id="iframe" />
)
React.useEffect(() => {
    let template = "<html><head></head><body><div id="content">hello world</div></body></html>"
    //really this is my response from an api call so it's a huge string of a complete HTML page 

    drawTemplateWindow(template)
})

这就是事情不起作用的地方......

const drawTemplateWindow = (string) => {
    let iframe = document.getElementById('iframe');
    let head = iframe.contentwindow.document.getElementsByTagName('head');
    let body = iframe.contentwindow.document.getElementsByTagName('body');
    let externalScripts = document.createElement('script');
    let editorScript = document.createElement('script');
    // set iframe content from template
    iframe.contentwindow.document.write(string)
    // add external EditorJS Script
    externalScripts.src = 'https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest'
    // add externalScripts to head
    head[0].appendChild(externalScripts)

    if (document.readyState === "complete" || document.readyState === "loaded") {
        console.log('have we loaded yet?')
        editorScript.type = 'text/javascript';
        editorScript.text = `
                // EditorJS should be defined in externalScripts include above
                let editor = new EditorJS('content') 
            `
    }

    // add editor script to end of body
    body[0].appendChild(editorScript);
}

我看到 externalScript 被附加到 Head,而编辑器脚本被附加到 body 的末尾。我还可以看到框架已完全加载的控制台日志。

我收到一个错误提示 EditorJS 未定义,或我抛出的任何脚本。我尝试创建一个带有警报函数的本地脚本并传递它,但它也失败了,并说该函数未定义。

在这里做错了什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)