[英]Not able to add dynamic script and style tag on dynamically create html and iframe
我有一個來自外部源的字符串。 現在我想將這個腳本和樣式標簽集成到我的應用程序中並執行 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並執行腳本功能嗎?
您正在將 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並設置sourxe
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.