1 内容页往原始页面新加脚本,目的是接受来自内容页的消息,并返回js变量
var myScript = document.createElement("script");
myScript.append('window.addEventListener("message", async function(event) { if (event.data.from === "extenstion") { var data = await new Promise(function(resolve) { resolve(window.wx.cgiData); });var message = { "from": "web", "to": "extenstion", "data": window.wx.cgiData };window.postMessage(message, "*"); }});');
document.body.append(myScript);
2 内容页新加监听,接受来自原始页的消息
window.addEventListener("message", function(event) {
if (event.data.from ==="web") {
console.log("cgiData", event.data.data);
}
});
3 给原始页发消息
var message = { "from": "extenstion", "to":"web", "data": "test" };
window.postMessage(message, "*");