【问题标题】:Dynamically add script tag and execute $(document).ready, without using iframe or document.write动态添加脚本标签并执行 $(document).ready,无需使用 iframe 或 document.write
【发布时间】:2021-06-13 13:40:43
【问题描述】:

我有一个来自 api 响应的字符串。现在我想将此脚本和样式标签集成到我的应用程序中并执行脚本。

  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>'

我尝试使用 iframe 加载它,我可以达到预期的效果

  const iframe = document.createElement('iframe');

   const html = `<body>${styleScriptText}</body>`;
   iframe.srcdoc = html;
 
   iframe.style.width = "47%";
   iframe.style.left = "25%";
   iframe.style.height = "100vh";
   iframe.style.position = "relative";
   document.getElementById("parentId").appendChild(iframe);

但我不想使用 iframe,因为它有未来的限制,我必须重定向到银行页面,当它返回时,整个应用程序都是 iframe,我不想要

接下来我尝试使用 document.write 如下

  const html = `<html>
        <head>
      
        </head>
          <body>
          ${styleScriptText}
         
          </body>
    </html>`;
document.open("text/html", "replace");
document.write(html);
document.close();

但上述方法的问题是我遇到了错误 通过 document.write 调用一个阻止解析器的跨站点(即不同的 eTLD+1)脚本 https:externalscript.js

如果我采取任何其他方法 $(document).ready 脚本中的函数不会执行。 几乎尝试了所有方法,但无法弄清楚如何加载和运行来自 api 响应的脚本。 这里的目标是我需要将脚本作为字符串并将其加载到 html 中并执行每个脚本文件

【问题讨论】:

    标签: javascript html angular api payment


    【解决方案1】:

    这应该有效,使用它需要您自担风险:

    const styleScriptText =
      '<style type="text/css">body {background: #000}</style><script type="text/javascript">alert("OK")</' + 'script' + '>';
    
    const insertStyleScriptText = () => {
        const div = document.createElement('div');
        div.innerHTML = styleScriptText;
        div.childNodes.forEach(child => {
            document.head.appendChild(child.cloneNode(true));
            if (child.tagName === 'SCRIPT')
                eval(child.textContent);
        });
    };
    &lt;button onclick="insertStyleScriptText()"&gt;insert StyleScriptText&lt;/button&gt;

    【讨论】:

    • 嗨@syduki 感谢您的回答,但我得到了,“ChildNode”类型上不存在属性“tagName”
    • 你在使用 TypeScript 吗? ['ChildNode'类型上不存在属性'tagName'](stackoverflow.com/questions/58742561/…),尝试更改为child.hasOwnProperty('tagName') &amp;&amp; child.tagName === 'SCRIPT'
    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 2016-07-14
    • 2014-03-10
    • 1970-01-01
    • 2022-11-23
    • 2015-08-21
    相关资源
    最近更新 更多