19

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.

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39
Null isTrue
  • 1,882
  • 6
  • 26
  • 46

2 Answers2

7

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.

Raphael Rafatpanah
  • 19,082
  • 25
  • 92
  • 158
0

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.

thompsonsj
  • 469
  • 4
  • 4
  • 1
    Thank you for the link. I was hoping to learn how I would implement that having it wired with a React App. – Null isTrue Jan 09 '19 at 19:04
  • This question IS or at least can be React specific. The answer in the link uses hardcoded styles or a separate link to a CSS file which may not be the case in a React application. – Devs love ZenUML Jan 28 '21 at 20:59
  • using Iframe within react is not straight forward... so this question is react specific – Mogli Mar 23 '21 at 08:23