2012-08-26 42 views
12

Làm cách nào để chuyển một số dữ liệu hoặc gọi hàm trên cửa sổ chính từ cửa sổ bật lên?Làm cách nào để chuyển dữ liệu vào cửa sổ cha mẹ từ cửa sổ bật lên?

Người dùng sẽ nhấp vào liên kết sẽ mở cửa sổ bật lên trên cùng một trang web, khi anh ấy kết thúc bằng cửa sổ bật lên, tôi muốn nó gửi dữ liệu mới trở lại cửa sổ chính hoặc gọi hàm trên cửa sổ chính .

+0

Ý anh là gì với _popup_, Bạn có nghĩa là một cửa sổ mở ra với ** _ blank **? – sQVe

+0

window.ppopup() –

Trả lời

17

Đối tượng window.opener là những gì bạn đang tìm kiếm, sử dụng nó từ bên trong cửa sổ bật lên của bạn như vậy để gọi một chức năng của cửa sổ cha mẹ:

window.opener.yourFunc() 
+0

sẽ không hoạt động trong IE khi cửa sổ bật lên là Tên miền chéo. – Salman

+0

Tôi thấy lỗi: Quyền bị từ chối truy cập thuộc tính yourFunc() – 123qwe

+0

http://stackoverflow.com/a/32617334/470749 là một ví dụ điển hình về hoạt động này. – Ryan

2

Đây là một niềm vui và dễ dàng giới thiệu rằng được lấy cảm hứng từ this answer to a similar question (nhưng được sửa đổi cho mục đích của riêng tôi để giúp điều tra the most difficult bug of my career).

Tạo 2 file (trong cùng thư mục) như sau:

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> 
Các vấn đề liên quan