業務需求
從後端取HTML 前端展示
要求
HTML不得被前臺全局樣式污染
解決方案
1、使用iframe 的 srcdoc
<iframe srcdoc="<p>這是HTML<p>" frameborder="0"></iframe>
2、 src=“text/html,xxxx”
<iframe src="data:text/html,<p>這是HTML<p>" frameborder="0"></iframe>
3、 在src中使用javascript (ueditor的方案)
<iframe
src="javascript:void(function(){
document.open();document.write('<p>這是HTML<p>');
document.close();}())" frameborder="0">
</iframe>
問題
微信瀏覽器中以上方案都無效 似乎對iframe的src都進行了特殊處理 (慘)
最終方案
直接對iframe的contentWindow進行操作 使用document.write 最終解決問題 此方法應該兼容性最好
<iframe src="about:blank;" id="target" frameborder="0"></iframe>
<script>
document.getElementById('target').contentWindow.document.write('<p>這是HTML<p>')
</script>
*百穀一番都沒有找到任何的解決方案 最終自己得出以下方案 記錄一下 也爲開發者們做一些微小的貢獻(笑)
如果我的文章有幫上什麼忙併且您也願意賞個臉 就掃碼領個紅包吧(~ ̄▽ ̄)~