部分Google Fonts在iframe innerHTML场景下不生效问题求助
问题根因
iframe 是独立的浏览上下文,和父页面的资源完全隔离。你在父页面 head 中引入的 Google Fonts 仅会被父页面加载,不会自动应用到 iframe 内部的文档。
之前 Comforter 字体可以正常生效,大概率是你的本地设备恰好安装了该字体,iframe 调用到了本地安装的字体资源;而你本地没有安装 Raleway 字体,就会直接 fallback 到系统默认的无衬线字体,出现你观察到的样式不符的情况。
解决方法
你需要主动将 Google Fonts 的引入注入到 iframe 自身的 head 节点中,修改你的 onLoad 函数即可:
function onLoad() { const iframeDoc = richTextFeld.document; iframeDoc.designMode = 'On'; // 给iframe注入Google Fonts引入 const fontLink = iframeDoc.createElement('link'); fontLink.rel = 'stylesheet'; fontLink.href = 'https://fonts.googleapis.com/css2?family=Raleway:wght@200&display=swap'; iframeDoc.head.appendChild(fontLink); iframeDoc.body.style.fontFamily = "'Raleway', sans-serif"; iframeDoc.body.style.fontSize = "16px"; iframeDoc.body.style.color = "#ff0000"; iframeDoc.body.innerHTML = "Some Text"; }
内容的提问来源于stack exchange,提问作者DevNick
相关产品推荐
相关产品推荐

