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
.
The easiest way to add the Styling to React component is to add it to the “index. html”. Every application has some common designs and styles which are applicable to the entire application such as font-size, text color, and other such properties.
An iframe has another scope, so you can't access it to style or to change its content with javascript. It's basically "another page". The only thing you can do is to edit its own CSS, because with your global CSS you can't do anything.
We can use inline CSS for the iframe by using CSS inside the iframe tag.
If it is static, you can simply use style tags inside the iframe markup, or better yet include an external stylesheet by linking to it in the iframe markup. If it is dynamic, you are best off using the jQuery JavaScript library as it is exceptionally good for handling CSS.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With