我知道由于各種原因不鼓勵使用 document.write,但是我正在使用它將以編程方式生成的 html 注入到 iframe 小部件中。
var iframe = document.createElement('iframe')
document.body.appendChild(iframe)
iframe.contentWindow.document.open()
iframe.contentWindow.document.write(generateHtml())
iframe.contentWindow.document.close()
這種方法非常適合我的用例,但是 Chrome 會像您期望的那樣警告 document.write:[Violation] Avoid using document.write().
是否可以壓制或滿足警告,還是我必須忍受它?
考慮到我嘗試過的其他方法,我相信這是將 html 注入 iframe 的最佳方法:
data:text/html; ...使用- 長度限制直接設定 src- 使用 html 設定 srcdoc - 這是我的后備方案,但瀏覽器支持可能是個問題
- 使用 btoa base64 編碼 html 并直接設定 src
data:text/html;base64,...- 這沒有正確編碼并產生Invalid regular expression: Range out of order in character class
感謝任何提示!
uj5u.com熱心網友回復:
另一種方法是使用DOMParser創建一個documentfrom ,然后用它修補檔案:htmliframe
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello</title>
</head>
<body>World!</body>
</html>
`;
const iframe = document.createElement('iframe');
iframe.addEventListener('load', () => {
const docOld = iframe.contentWindow.document;
const docNew = new DOMParser().parseFromString(html, 'text/html');
docOld.insertBefore(docNew.doctype, docOld.firstChild);
docOld.replaceChild(docNew.documentElement, docOld.documentElement);
});
document.body.appendChild(iframe);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/504919.html
