0

I used CodeMirror to make some tests about an IDE in browser, is working well but is there any possiblity to check if the <h2>test</h2> is red ( have a style of color red ), that <h2>test</h2> is from the text editor, see the next image to have a clear understanding about what I am saying.image

I'm using React JS here is App.js

import React, { useState, useEffect } from "react";
import Editor from "./Editor";
import "./main.css";
import useLocalStorage from "./useLocalStorage";
function App() {
  const [html, setHtml] = useLocalStorage("html", "");
  const [srcDoc, setSrcDoc] = useState("");

  useEffect(() => {
    const timeout = setTimeout(() => {
      setSrcDoc(`
      <html>
      <head></head>
      <body>${html}</body>
      </html>
    `);
    }, 300);
    return () => clearTimeout(timeout);
  }, [html]);
  return (
    <div className="App">
      <div className="pane">
        <Editor language="xml" value={html} onChange={setHtml} />
      </div>
      <div className="result">
        <iframe
          id="myframe"
          srcDoc={srcDoc}
          title="output"
          sandbox="allow-scripts"
          frameBorder="0"
          width="100%"
          height="100%"
        />
      </div>
      <button className="btn">
        RUN
      </button>
    </div>
  );
}

export default App;

In Editor.JS is only the CodeMirror syntax for the editor.

What I tried:

  • To get the element with document.querySelector("#test") in useEffect, is not working.

  • Using document.getElementById("myframe").contentWindow.document is throwing me an error: "SecurityError: Blocked a frame with origin "http://localhost:3000" from accessing a cross-origin frame.", I couldn't find an answer for that.

Tudor Alexandru
  • 236
  • 1
  • 12

1 Answers1

0

you can use a ref for this using useRef hook

import React, { useState, useEffect,useRef } from "react";
function App() {
  const iframeRef= useRef()

  useEffect(() => {
     const h1 = iframeRef.current.contentWindow.document.querySelector('h1')
  }, [iframeRef.current]);

  return (
        <iframe
          ref={iframeRef}
          id="myframe"
          srcDoc={srcDoc}
          title="output"
          sandbox="allow-scripts"
          frameBorder="0"
          width="100%"
          height="100%"
        />
}

export default App;

and concerning this error "SecurityError: Blocked a frame with origin "http://localhost:3000" from accessing a cross-origin frame.", I couldn't find an answer for that.
check this asnwer for a work around SecurityError: Blocked a frame with origin from accessing a cross-origin frame

سعيد
  • 1,024
  • 3
  • 18