2012-08-26 6 views
12

Come posso passare alcuni dati o chiamare una funzione nella finestra principale da una finestra popup?Come passare i dati alla finestra principale dalla finestra popup?

L'utente fa clic su un collegamento che aprirà un popup sullo stesso sito Web, una volta terminato con il popup, voglio che invii i nuovi dati alla finestra padre, o chiami una funzione nella finestra padre .

+0

Che cosa si intende con _popup_, intendi una finestra aperta con ** _ vuoto **? – sQVe

+0

window.ppopup() –

risposta

17

L'oggetto window.opener è quello che stai cercando, lo usavano dall'interno del popup come modo per chiamare la funzione della finestra padre:

window.opener.yourFunc() 
+0

non funziona in IE quando la finestra popup è Cross Domain. – Salman

+0

Vedo errore: Autorizzazione negata per accedere alla proprietà yourFunc() – 123qwe

+0

http://stackoverflow.com/a/32617334/470749 è un buon esempio di questo funzionamento. – Ryan

2

Ecco un divertente e facile demo che è fortemente ispirato da this answer to a similar question (ma modificato per i miei scopi per aiutare a indagare su the most difficult bug of my career).

creare 2 file (nella stessa directory) come segue:

Parent.html

<button type="button" onclick="popup('popup.html', '', 800, 200);">Add My Card</button> 
=&gt; 
<span id="retrievedData">No data yet.</span>  
<script> 
    function popup(url, title, width, height) { 
     var left = (screen.width/2) - (width/2); 
     var top = (screen.height/2) - (height/2); 
     var options = '';  
     options += ',width=' + width; 
     options += ',height=' + height; 
     options += ',top=' + top; 
     options += ',left=' + left;  
     return window.open(url, title, options); 
    } 

    function setData(data) { 
     console.log(data); 
     var strData = JSON.stringify(data); 
     document.getElementById('retrievedData').innerHTML = strData; 
     var requestBinUrl = 'http://requestb.in/18u87g81'; 
     window.location.href = requestBinUrl + '?data=' + strData; 
    } 
</script> 

popup.html

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<form id="popupForm" name="f">  
    <select id="urlField" name="url"> 
     <option> 
      http://date.jsontest.com/ 
     </option> 
     <option> 
      http://time.jsontest.com/ 
     </option> 
     <option> 
      http://md5.jsontest.com/?text=HereIsSomeStuff 
     </option>  
    </select> 
    <div><input type="submit" /></div>  
</form> 
<script> 
    $('#popupForm').submit(function(e) { 
     e.preventDefault(); 
     var url = $('#urlField').val(); 
     console.log(url); 
     $.ajax({ 
      url: url 
     }).then(function(data) { 
      console.log(JSON.stringify(data)); 
      window.opener.setData(data); 
      window.close(); 
     }); 
    });  
</script>