Implementing CSS styles on iframe content in React

Is there a way to style the content loaded by an iframe in a React app using CSS?

I'm facing an issue with loading external content into my app, as the styles are outdated and I want to customize them.

See Example Below: (Please note that the src content of the <iframe/> has been replaced with dummy data for demonstration purposes, but the problem remains 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);

Check out this code sandbox for a visual representation of the problem.

In the provided example, I aim to change the color of h1#firstHeading to red.

Answer ā„–1

In a typical scenario, this task is accomplished using JavaScript:

document.querySelector('iframe').contentWindow.document.querySelector("h1#firstHeading").style.color = "red";

Nevertheless, such actions are restricted for cross-origin iframes.

Error: A frame from origin "..." was stopped from accessing a cross-origin frame.

Answer ā„–2

This query is not exclusively related to React, and you can find guidance on how to apply CSS to an iframe at this link.

In general, while there may be certain tricks and alternative methods, a dependable solution is often elusive unless you possess authority over the embedded website or if the site has relaxed CORS settings.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to transform a JSON data-storing object into an array within Angular?

I am currently working on developing a machine learning model using tensorflow.js, but I have encountered a roadblock. The issue I am facing is that I have stored my JSON content in a local object, but for it to be usable in a machine learning model, I ne ...

Steps for executing a Node script are as follows:

My task is to execute a node script that will remove an object from an external API. This can be achieved by running the following command: node server.js Customer55555 Upon execution, the specified object should be deleted successfully. To interact wit ...

Obtaining information from an API in JSON format

I'm currently working on integrating a basic Stock API into JSFiddle.net using the Quandl API: When I use the current format of ".csv" as shown below, I receive a CSV file. However, if I switch the format to ".json" in my API, how can I retrieve the ...

JavaScript Array - Error: Unable to access property 'length'

Currently, I am working on a Cordova/Phonegap application that utilizes an internal database. Typically, after executing a query, I would retrieve and review the results as shown below: for (var i=0;i<results.rows.length;i++) { name=(results.rows. ...

Oops! Make sure to explicitly allow the dependency @types/html2canvas by adding it to the "allowedNonPeerDependencies" option

After installing the html2canvas package in my Angular library project, I encountered an error when compiling in production mode using the command ng build --prod. The specific error message is as follows: ERROR: Dependency @types/html2canvas must be exp ...

Unable to extract the property 'displayName' from 'undefined' since it is not defined

Every time I try to register, I encounter the following error message: "Cannot destructure property 'displayName' of 'undefined' as it is undefined." Furthermore, even when I adjust the order in the try block on authSlice.js, Firebase r ...

Click-o-Meter: Tracking Button Presses

Iā€™m looking to develop a button click counter that increases every time it is downloaded. I want to implement this functionality without using a database. Here's the code snippet: <?php $counterFile = 'path/to/counter.txt' ; ...

Encountering a Nextjs 404 error when trying to reload or refresh the page

In my front-end application, I am utilizing Nextjs alongside dotnet core 3.1 for the Web API. Some pages in the app are static while others are dynamic, and I have successfully implemented this functionality by following the official documentation. During ...

Exploring the power of utilizing the Graphics class and the DrawRectangle method with negative x and y coordinates within web applications using C#

Problem: I am facing a challenge with replicating the configuration of a solar power plant field on a webpage using a set of rectangles for mirrors and receivers. My task is to dynamically add rectangles to webpages with specified X, Y, width, and height p ...

React-Markdown is throwing an error that states: "ES Module must be imported in order to load

Trying to integrate react-markdown into my Next.js project resulted in an immediate error when attempting to use it. Here is the code snippet: import React from 'react' import ReactMarkdown from 'react-markdown' export function Markd ...

Executing a JavaScript function with no event

This particular code snippet is taken from a.jsp: <script type="text/javascript" > function checkDates(date1, date2) { var x = date1.split('/') var y = date2.split('/') var firstDate = new Date(x[2],x[0 ...

Simple steps to dynamically alter CSS styles according to the current URL

I am working on a website where I want users to be able to change the background image and other CSS elements. Currently, my approach is to have multiple HTML pages that users can switch between using a dropdown menu and reload the page. For example: hre ...

Exploring the life cycle of components in React with the added functionality of connecting with react-redux and

It is common knowledge that the order of execution in React components is constructor -> componentWillMount -> componentDidMount. However, when incorporating Redux and accessing Redux properties in our component life cycle, what is the sequence in w ...

Declaring named exports dynamically in TypeScript using a d.ts file

I have developed a collection of VueJs components in TypeScript and I want to be able to use them globally in my Vue instance using Vue.use(library), or individually through named imports in Vue components. While everything functions correctly, I am facin ...

html form altering user's name upon submission

I encountered a situation where I had a form consisting of survey questions with radio button answers pulled from an Excel spreadsheet. The unique identifier for each question was determined by the ID field inputted by a human. In this case, the name of e ...

A guide to creating interactive elements that can be dragged using touchscreens and mouse controls

My drag and drop application code works perfectly on desktop, but when I try to use it on mobile, the drag events do not function as expected. I understand that touch events are necessary, but I am unsure how to set them up and implement the required fun ...

Revamp your AngularJS controller for a fresh new look

How can a controller be refreshed in Angular? Take into account the scenario below: <div ng-controller="MsgCtrl" ng-repeat="m in messages">{{m}}<br></div> <script> var ws = new WebSocket(something, something); function MsgCtrl($sco ...

Error encountered while using parameters in Angular service

I have been struggling to pass two variables from an angular service to an MVC controller, but I keep encountering errors. The latest error I'm getting is that 'compName' doesn't exist. I've spent hours trying to debug the issue us ...

The Axios patch method encounters an issue where the baseURL is not retrieved

I have encountered a problem while trying to update the base URL in my Axios patch request. Despite specifying the new baseURL in the stageReceiver method, it continues to use the default baseURL (which is set when running npm serve). import axios from &q ...

Tips for activating a deactivated input field in ReactJS

I am trying to create a feature where my textfields are automatically disabled, but can be enabled for editing by clicking an 'Edit' button. Clicking the button again should disable the textfields and save any edits made. I have experimented with ...