I'm using StackBlitz to embed an iframe into my React app on the front end. Now, I'm trying to access the embedded iframe HTML elements with javascript when clicking on the button Submit answer.
However, I get the following error: Blocked a frame with origin "http://localhost:3000" from accessing a cross-origin frame. I know this is a security feature implemented by Chrome itself. I do trust this site & I would like to find a workaround for this issue for POC, which I'm working on.
How can I accomplish to get access to the embedded iframe & its HTML elements within?
A few things:
I do not care if the solution provided has security issues. I trust this website & it's also for a personal/toy/POC project.
I'm looking for an easier/simpler solution to solve this issue.
That being said, I'm open to secure/proper solutions, but I am prioritizing speed over best practices, etc...
This is my code so far:
public/index.html
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="coding-playground"></div>
<div id="root"></div>
</body>
**src/App.js**
import "./App.css";
import { useState } from "react";
import sdk from "@stackblitz/sdk";
function App() {
// eslint-disable-next-line no-unused-vars
const [challengePassed, setChallengePassed] = useState("");
sdk.embedProjectId("coding-playground", "<redacted-characters>", {
forceEmbedLayout: true,
openFile: "src/App.js",
});
const handleClick = () => {
const codeSampleWindow = document
.querySelectorAll("iframe")[0]
.contentWindow.document.body.getElementById("root");
// can't access this code sample window due cross-domain policy
console.log(codeSampleWindow);
// pseudo code below
// if (codeSampleWindow.querySelector("h1").innerText === "Hello World") {
// setChallengePassed("Challenge Passed");
// }
};
return (
<>
<button className="submit-answer" onClick={handleClick}>
Submit Answer
</button>
{challengePassed ? (
<div className="challenge-passed">Challenge passed!</div>
) : (
<div className="challenge-failed"> Challenge is not passed!</div>
)}
</>
);
}
export default App;
This is what my app currently looks like: