0

Can you get the value of an input of an iFrame with the keyword this?

This is how I'm trying to do it:

window.addEventListener('DOMContentLoaded', (event) => {
  //console.log(document.querySelector('#hs-form-iframe-0').contentWindow.document.body.querySelector('.hs_email'))
    document.querySelector('#hs-form-iframe-0').contentWindow.document.body.querySelector('.hs_email').addEventListener('keyup', function() {
      console.log(this)
      console.log(this.value)
      if (this.value == undefined) {
        console.log('im empty')
        document.querySelector('#hs-form-iframe-0').contentWindow.document.body.querySelector('.hs-form-field').style.display = 'block';
      } else {
        console.log('im not empty')
      }
    })
});

The evaluation of console.log(this.value) is ALWAYS undefined - why? even if I type. in a non iFrame example this works:

window.addEventListener('DOMContentLoaded', (event) => {
    document.getElementById('text-input').addEventListener('keyup', function() {
      console.log(this)
      console.log(this.value)
    })
});
<input id="text-input">

Get value of input field inside an iframe

document.getElementById("idframe").contentWindow.document.getElementById("idelement").value;

Which has 5 upvotes but a comment with 14 upvotes says:

Browsers will prevent JavaScript from accessing a cross-origin frame. –

I'm not getting any cross origin errors in my code it just says undefined all the time.

I'm super confused here because in the above linked answers it says jQuery with 33 upvotes.

Get a value from Iframe into mainPage

The first thing you have to tell is is:

Is the iframe hosted on the same http host as the parent website? If not, you will run into javascripts same origin protection, read about it at: http://en.wikipedia.org/wiki/Same_origin_policy

In short: You will not be accessible to access the content. But wait! There is a workaround which I will explain after dealing with the second case, where the http host is the same!

So lets talk about that second case. Well then the job is easy...

You just have to access the iframe (probably give the iframe tag an id "example"). Then you can access the window using example.contentWindow.document or example.contentDocument

Which is what I'm doing but still not working.

I'm confused, so can you or can you not get a value of an input in an iFrame from a different domain?

kawnah
  • 2,805
  • 6
  • 43
  • 84

0 Answers0