Send DropDown value to Iframe

1

How do I send a value from a Drop Down to an [ IFRAME ]?

I'm recovering the value like this:

function mandaIframe() {
    pai = parent.document.form1; // especifica o elemento de id="formularioX", dentro do documento que é pai da página.
    var idcat = pai.varField_idcat.value; // captura o valor do campo de id="numero", dentro do elemento de id="formularioX", dentro do documento que é pai.
}

But I'm having trouble sending it to Iframe.

    
asked by anonymous 03.07.2018 / 16:59

2 answers

2

You can change the src of iframe by taking the value selected in the dropdown and passing that value as a parameter in the URL of iframe :

function mandaIframe() {
   var idcat = document.querySelector("#numero").value; // valor selecionado no dropdown
   document.querySelector("iframe").src = "pagina.asp?id="+idcat; // alterar o src do iframe
}

No iframe you get the value via ASP with request :

<%
idcat = request("id");
%>

With the variable idcat getting the value of id in the URL, you do what you want.

    
03.07.2018 / 17:54
0

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>
    
03.07.2018 / 19:08