Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 289
Null isTrue Avatar asked Jan 09 '19 18:01

Null isTrue


People also ask

Can you add style to React component?

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.

Can I style content in an iframe?

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.

Can you style an iframe with CSS?

We can use inline CSS for the iframe by using CSS inside the iframe tag.

How do I add content to iframe CSS?

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.


1 Answers

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.

like image 104
Raphael Rafatpanah Avatar answered Oct 11 '22 04:10

Raphael Rafatpanah