微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将 javascript 注入并执行到 iframe

如何解决将 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 举报,一经查实,本站将立刻删除。