Iframe 未从 chrome 浏览器中同一域下的 link 标记加载 css
Iframe not loading the css from link tag under same domain in chrome browser
我正在使用 javascript
.
将 iframe
动态添加到 html 文档
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.contentWindow.document.body.innerHTML = document.querySelector('#section-to-print').innerHTML;
当我使用 link
标签从 same domain
添加 css
到 iframe
头部时,样式没有加载。
let link = document.createElement("link");
link.href = "https://localhost:5001/css/invoice-receipt.css"; /**** your CSS file ****/
link.rel = "stylesheet";
link.type = "text/css";
iframe.contentWindow.document.head.appendChild(link);
但是当我使用 style
标签添加 css
时它起作用了。
var styles = document.createElement("style");
styles.innerHTML = `html, body {
width: 2.7in;
margin: 0 auto;
height: max-content;
}`;
iframe.contentWindow.document.head.appendChild(styles);
问题是我想动态加载不同的样式表,但无法通过 link 加载。请协助解决我遗漏的问题。
我使用下面的 script
.
使它起作用
var bodyScript = document.createElement("script");
bodyScript.innerHTML = `fetch('https://localhost:5001/css/invoice-receipt.css')
.then(response => response.text())
.then(data => {
var head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
head.appendChild(style);
style.type = 'text/css';
style.appendChild(document.createTextNode(data));
});`;
iframe.contentWindow.document.body.appendChild(bodyScript);
我正在使用 javascript
.
iframe
动态添加到 html 文档
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.contentWindow.document.body.innerHTML = document.querySelector('#section-to-print').innerHTML;
当我使用 link
标签从 same domain
添加 css
到 iframe
头部时,样式没有加载。
let link = document.createElement("link");
link.href = "https://localhost:5001/css/invoice-receipt.css"; /**** your CSS file ****/
link.rel = "stylesheet";
link.type = "text/css";
iframe.contentWindow.document.head.appendChild(link);
但是当我使用 style
标签添加 css
时它起作用了。
var styles = document.createElement("style");
styles.innerHTML = `html, body {
width: 2.7in;
margin: 0 auto;
height: max-content;
}`;
iframe.contentWindow.document.head.appendChild(styles);
问题是我想动态加载不同的样式表,但无法通过 link 加载。请协助解决我遗漏的问题。
我使用下面的 script
.
var bodyScript = document.createElement("script");
bodyScript.innerHTML = `fetch('https://localhost:5001/css/invoice-receipt.css')
.then(response => response.text())
.then(data => {
var head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
head.appendChild(style);
style.type = 'text/css';
style.appendChild(document.createTextNode(data));
});`;
iframe.contentWindow.document.body.appendChild(bodyScript);