Reputation: 1906
On a React app, how could I apply CSS styles to the src content that is been loaded by iframe?
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.
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
.
Upvotes: 19
Views: 39678
Reputation: 498
This question is not React specific, and is answered at How to apply CSS to 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.
Upvotes: -3
Reputation: 19967
Normally, you'd do this with JavaScript:
document.querySelector('iframe').contentWindow.document.querySelector("h1#firstHeading").style.color = "red";
However, this isn't allowed for cross-origin iframes.
Error: Blocked a frame with origin "..." from accessing a cross-origin frame.
Upvotes: 7