Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
Write inline javascript in iframe

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');").

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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();
    }
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!