Is it possible to access html elements contained in an iframe?

I want to access the form data of an html page that is displayed in an iframe from within sketch.js.

Is this possible?

Fullscreen view https://editor.p5js.org/Bassam/full/mwQs-ReOk
Code https://editor.p5js.org/Bassam/sketches/mwQs-ReOk

You can select an iframe with: frame.elt.contentWindow.document
I added elt to select HTML DOM element, not p5js element.

There is an issue with the timing of selecting iframe elements because it may not be ready when you want to use it. I found a neat solution from https://stackoverflow.com/questions/60461930/checking-if-iframe-contents-are-loaded

let frame;
let cnv;
let frameDoc

function setup() {
  frame = createElement("iframe", "")
  frame.attribute("src", "demo.html")
  frame.attribute('id', 'myframe')

  // https://stackoverflow.com/questions/60461930/checking-if-iframe-contents-are-loaded
  frame.elt.addEventListener("load", function() {
    frameDoc = frame.elt.contentWindow.document
    // console.log(frameDoc)

    const p = frameDoc.querySelector('p')
    p.style.color = 'red'
  });
}
2 Likes