[英]React - How to apply CSS styles to iframe content
On a React app, how could I apply CSS styles to the src content that is been loaded by iframe?在 React 应用程序中,如何将 CSS 样式应用于 iframe 加载的 src 内容?
I have an app loading external content, but the styles are really dated and I'd like to overwrite it.我有一个加载外部内容的应用程序,但样式确实过时了,我想覆盖它。
Example Bellow: (Please note I replaced the src
content of the <iframe/>
, with some dummy data, however, the problem is still the same.示例波纹管:(请注意,我用一些虚拟数据替换了<iframe/>
的src
内容,但是,问题仍然相同。
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class Frame extends React.Component {
componentDidMount() {
document
.querySelector("iframe")
.contentWindow.document.querySelector("h1#firstHeading").style.color =
"red";
}
render() {
return (
<iframe
title="How Can I overwrite the styles from the src content?"
src="https://en.wikipedia.org/wiki/Herbie_Hancock"
width="90%"
height="500px"
scrolling="no"
/>
);
}
}
function App() {
return (
<div className="App">
<Frame />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Here's a code sandbox illustrating my problem.这是一个代码沙箱,说明了我的问题。
In the sandbox example, I'd like to change the h1#firstHeading
color to red
.在沙箱示例中,我想将h1#firstHeading
颜色更改为red
。
Normally, you'd do this with JavaScript:通常,您会使用 JavaScript 执行此操作:
document.querySelector('iframe').contentWindow.document.querySelector("h1#firstHeading").style.color = "red";
However, this isn't allowed for cross-origin iframes.但是,跨域 iframe 不允许这样做。
Error: Blocked a frame with origin "..." from accessing a cross-origin frame.错误:阻止了源为“...”的框架访问跨源框架。
This question is not React specific, and is answered at How to apply CSS to iframe?这个问题不是 React 特定的,在如何将 CSS 应用到 iframe? . .
Overall, although there may be some hacks and workarounds, there isn't a reliable solution unless you have control over the website you are embedding or the website has relaxed CORS settings.总体而言,尽管可能存在一些黑客和变通方法,但除非您可以控制要嵌入的网站或网站具有宽松的 CORS 设置,否则没有可靠的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.