In general, it is ideal that communication between different documents be done using messaging.
Let's take the following use case, the page should send a text ( value
from textarea
) to iFrame
, iFrame
should update its content based on received text, notify the parent page so that it clears textarea
.
To achieve this result, you can make use of window.postMessage(...)
and window.addEventListener('message', function (evt) { ... })
// html/script do iFrame
var html = '
<html>
<head><\/head>
<body>
<div id="box">
<\/div>
<script type='text/javascript'>
var box = document.getElementById('box');
window.addEventListener('message', function (evt) {
if (evt.origin !== 'null') // modifique o 'null' para a dominio do iframe.
return;
box.textContent = evt.data
window.parent.postMessage('OK', '*') // modifique o '*' para a dominio da pagina pai.
})
<\/script>
<\/body>
<\/html>
';
// criando a pagina a ser carregada no iFrame.
var blob = new Blob([html], { type: 'text/html' })
document.querySelector('iframe').src = URL.createObjectURL(blob)
var iframe = document.querySelector('iframe')
var textarea = document.querySelector('textarea')
var button = document.querySelector('button')
// enviando uma mensagem para o iframe
button.addEventListener('click', function (evt) {
iframe.contentWindow.postMessage(textarea.value, '*') // modifique o '*' para a dominio do iframe.
})
// recebendo uma mensagem do iframe
window.addEventListener('message', function (evt) {
if (evt.origin !== 'null' || evt.data !== 'OK') // modifique o 'null' para a dominio da pagina.
return;
textarea.value = '';
})
textarea, iframe {
width: 300px;
height: 120px;
}
<div>
<textarea></textarea>
<iframe src='#'></iframe>
</div>
<div><button>Copiar</button></div>