简体   繁体   English

从一个页面发送函数并在另一个页面上运行它

[英]Send a function from one page and running it on another

I have access to both pages on my localhost. 我可以访问本地主机上的两个页面。 The page I want to send the function to is in an frame on the page I want to send it from. 我要将函数发送到的页面位于我要发送它的页面上的一个框架中。 Would postmessage work and setting up an event listener in the receiver/iframe page? postmessage会在接收器/ iframe页面中工作并设置事件监听器吗? The function is: 功能是:

 ipa.searchByString(query);

Listener syntax: 监听器语法:

ipa.addListener('query', myAppEventHandler);
};

Yes you could send a function as a string from one page to another, but that won't work well if the function dependa on other functions variables. 是的,您可以将函数作为字符串从一个页面发送到另一个页面,但如果该函数依赖于其他函数变量,那么这将无法正常工作。 And generally I don't think you want that here. 一般来说,我认为你不想要这个。 Instead propagate the handler to the messaging channel: 而是将处理程序传播到消息传递通道:

 ipa.addListener('query', function proxy(data) {
   iframe.postMessage({ name: "ipa", data });
 });

Then receice it on the other page: 然后在另一页上接收它:

 window.onmessage = e => {
   const { name, data } = e.data;
   if(name === "ipa") myAppEventHandler(data);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM