Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

91
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda