React JS是否有可能检查iframe中的特定元素是否具有正确的样式

问题描述

我使用CodeMirror对浏览器中的IDE进行了一些测试,效果很好,但是是否有可能检查<h2>test</h2>是否为红色(具有红色的样式),<h2>test</h2>是来自文本编辑器,请看下一张图片,以清楚地了解我在说什么。

image

我正在使用React JS,这里是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;

在Editor.JS中,JS仅为编辑器的CodeMirror语法。

我尝试过的事情:

  • 获取useEffect中带有document.querySelector("#test")的元素,将无法正常工作。

  • 使用document.getElementById("myframe").contentwindow.document会向我抛出错误:“ SecurityError:阻止了起源为“ http:// localhost:3000”的框架访问跨域框架。”,我找不到一个答案。

解决方法

您可以使用useRef钩子为此添加引用

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;

并涉及此错误“ SecurityError:阻止了起源为“ http:// localhost:3000”的框架访问跨域框架。”,我找不到相应的答案。
检查此解决方案以解决SecurityError: Blocked a frame with origin from accessing a cross-origin frame