【问题标题】:Not able to add dynamic script and style tag on dynamically create html and iframe无法在动态创建 html 和 iframe 时添加动态脚本和样式标记
【发布时间】:2020-12-23 17:30:46
【问题描述】:

我有一个来自外部来源的字符串。现在我想在我的应用程序中集成这个脚本和样式标签并执行 scipt。

  const styleScriptText = '<style type="text/css">#checkoutmodal .checkoutmodal-box{background:#FFF !important}</style><script src="https://someurl/lib/jquery.min.js" type="text/javascript"></script><script type="text/javascript">$(document).ready(function() { console.log("test")});</script>'

为了实现这一点,我创建了一个动态 html 并将其附加到 iframe 中

 const html = `<html>
        <head>
       ${styleScriptText}
        </head>
          <body>
          
         
          </body>
    </html>`;
    const iframe = document.createElement('iframe');
    iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
    document.body.appendChild(iframe);

现在的问题是,当我检查这个 iframe 时,我没有得到脚本和样式标签,请查找附件

我不确定我做错了什么,任何帮助都非常感谢。

编辑:除此之外,我们还有什么方法可以在应用程序中styleScriptText 并执行脚本功能?

【问题讨论】:

  • 双击您的源代码,但浏览器对属性值中显示的字符数有限制
  • @EugenSunic 即使在编辑为 html 之后也不存在我只得到
  • 但它不会在那里它会在 src 因为你把它放在那里......

标签: javascript html angular iframe


【解决方案1】:

您将 html 插入到 iframe 的 src 属性中,而不是 iframe 内容中

const styleScriptText = '<style type="text/css">#checkoutmodal .checkoutmodal-box{background:#FFF !important}</style><script src="https://someurl/lib/jquery.min.js" type="text/javascript"></script><script type="text/javascript">$(document).ready(function() { console.log("test")});</script>'

定义html并设置来源

const html = `<html>
        <head>
       ${styleScriptText}
        </head>
          <body>
          
         
          </body>
    </html>`;
const iframe = document.createElement('iframe');
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);

设置 iframe 内容

var doc = iframe.contentWindow.document;
doc.open();
doc.write(html);
doc.close();
document.body.appendChild(iframe);

【讨论】:

    猜你喜欢
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    相关资源
    最近更新 更多