How to interact with an iframe

1

Good day, evenings or evenings, I have the doubt of whether it is possible to run functions from an iframe, the situation is the following, in my work we provide a chat service but the page where we attend the chats has 2 windows to attend the chats, one of them is protected with iframe and the other does not, making tests I see that a function in js runs on both pages, then I program a page in which I have an iframe and in that iframe is the chat page that does not is protected by the iframe, the question is that the page that is protected from the iframes has the button that changes your status from online to ofline and vice versa, that button triggers the following function "javascript: PortalUI.userStatus.saveStatus (this); " and I realize that by concola I can run the function on the other page that does not have the button, my question is if from my page I can integrate a button that by clicking you run that function

    
asked by Erick Hammett 09.10.2018 в 23:29
source

1 answer

0

Yes, you can. You must call the iFrame using its ID, and calling the contentWindow object of that iframe:

HTML:

<button type="button" id="boton">Boton fuera del iframe</button>
<iframe id="iframe1" width="200" height="200">
    <body>Esto es un iframe</body>
</iframe>

JS:

function agregarScriptEnIframe(){
    let scriptNuevo = document.createElement('script');
    scriptNuevo.setAttribute('src','script_iframe.js');
    document.getElementById('iframe1').contentWindow.document.body.appendChild(scriptNuevo);
}

document.getElementById('boton').addEventListener('click',function(){
    document.getElementById('iframe1').contentWindow.alerta('Esta alerta del iframe se llamó desde afuera del iframe');
});

script_iframe.js:

function alerta(texto){
    alert(texto);
}
    
answered by 09.10.2018 / 23:39
source