How can I send an event from parent window to its child window?

做~自己de王妃 提交于 2019-12-11 11:15:05

问题


I want to send some event/data from parent window to its child window. How can I do so? I have tried postMessage, but it didn't work.


回答1:


It has worked now, earlier I was doing some syntax mistake. Here is the correct code for the same.

//parent Window
childWindow=window.open("http:/localhost/abcd.php","_blank","width=500,height=500");
childWindow.postMessage('message',"http://localhost:80/child.php");


//child Window
var newUrl='';
window.addEventListener(
 "message",
 function(e) { 

console.log(e.data);//your data is captured in e.data 
}, false);



回答2:


If the child window you're referring to is an iFrame, then postMessage is the method you're stuck with.

Without seeing any of the code you've tried, it's hard to say what about your particular usage of postMessage isn't working – however, here is a link to a working postMessage example from an MDN article, as well as an article with a fully functional example you can dissect the code from.

One of these should be able to show you why your implementation isn't working.



来源:https://stackoverflow.com/questions/49516556/how-can-i-send-an-event-from-parent-window-to-its-child-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!