0

I have code that can be reduced to this:

<script>
    function write_to_iframe(){ 
        let nw = document.getElementById("mysrc");
        let myframe = document.getElementById("myframe");
        myframe.contentWindow.document.body.innerHTML = nw.innerHTML;
    }
</script>

<iframe id="myframe" width="230" height="95"></iframe>

<div id="mysrc">
    <script>
        function hello(){ 
            alert("hello world");
        }
    </script>
    <a href="#" onclick="hello(); return false;">SayHello</a><br>
</div>

It writes the code in the div to the iframe. That part seems to work. However, when I click the SayHello link in the iframe I get a javascript error that the function hello() cannot be found.

What is going wrong here? And how can I declare an inline javascript function in the frame that works.

I am not interested in external javascript files or code that puts everything in the link (like onclick="javascript:alert('hi');").

Dropout
  • 13,653
  • 10
  • 56
  • 109
user2587656
  • 309
  • 3
  • 5

1 Answers1

0

I would reconsider using an iframe with innerHTML and trying to call a function in the main document from it. The support can vary in different browsers, iframes access to its parent is very limited. If both those things are on the same domain then you don't break CORS policy and you can do more but still there are better options.

If you insist on using iframe, I would consider creating an external path for it (same domain) ex. iframe/embed.html put HTML there normally, then change location after click triggered inside to iframe/embed.html#callHello. And in main document I would add eventListner to detect location change.

const iframe = document.getElementById("iframeId");

window.open("https://example.com/iframe/embed.html", "iframeId");


iframe.addEventListener("load", () => {
    if (iframe.contentWindow.location.href.includes('#callHello')) {
        hello();
    }
});
Deykun
  • 1,298
  • 9
  • 13