1

This sounds like a simple task but I'm finding the solution oddly hard to nail down.

All I want to do is populate a text input box in the parent window with data from an iframe, using a button click inside the iframe. And yes, both pages are on the same domain.

Tried various solutions with raw JS, Jquery, Ajax etc with no joy. I have found a solution to populate a <div> container, but applying the same target id to a text input does not work.

I've also successfully used this Jquery script from the parent page to send data to the iframe, but can't work out how to do the reverse (iframe to parent)

<script> 
    $(document).ready(function(){
        $('#submit').click(function(){
            var iframe = document.getElementById('myiframe');
            var doc = iframe.contentDocument || iframe.contentWindow.document;
            var elem = document.getElementById('source');
            doc.getElementsByName('target')[0].value = elem.value;
        });
    });
</script>

The simplified setup.

parent.html:

<!DOCTYPE html>
<html>
<body>

<iframe id="myiframe" frameborder="1" src="child.html"></iframe>

<form>
Iframe data populates here: <input type="text" name="target" id="target"> 
</form>

</body>
</html>

child.html:

<!DOCTYPE html>
<html>
<body>

<form>
Iframe data is input here:  <input type="text" name="source" id="source"> 
<button type="button" onclick="functionToSendSourceToParent();">
</form>

</body>
</html>

1 Answers1

0

Isn't it simple ? On local except Chrome works like this:

parent.html:

<!DOCTYPE html>
<html>
<body>

<iframe id="myiframe" frameborder="1" src="child.html"></iframe>

<form>
Iframe data populates here: <input type="text" name="target" id="target"> 
</form>

</body>
</html>

child.html

<!DOCTYPE html>
<html>
<script>
function functionToSendSourceToParent() {
    var inp = document.getElementsByName("source")[0].value;
    parent.document.getElementsByName("target")[0].value = inp;
}
</script>
<body>

<form>
Iframe data is input here:  <input type="text" name="source" id="source"> 
<button type="button" onclick="functionToSendSourceToParent();">Send2Parent</button>
</form>

</body>
</html>

Chrome console reports:

child.html:6 Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.<br/>
    at functionToSendSourceToParent (file:///X:/child.html:6:12)<br/>
    at HTMLButtonElement.onclick (file:///X:/child.html:13:65)<br/>
Jan
  • 2,178
  • 3
  • 14
  • 26
  • Here answer 4 Chrome https://stackoverflow.com/questions/29983786/blocked-a-frame-of-origin-null-from-accessing-a-cross-origin-frame-chrome/29984435#29984435 – Jan Aug 26 '19 at 07:08
  • Fantastic! Thank you Tom. And yes, it is simple for anyone with a working knowledge of JS (which I don't have). I found several variations of this theme, but they all crashed when I started trying to adapt them to this task. This does exactly what I need. You da man. – Mandrake Slink Aug 26 '19 at 07:22