花钱买到的技术,chrome扩展 内容页获取原始页面的js变量
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);
其中附加的代码格式化后如下
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, "*"); } });
收到来自内容页的消息后,返回指定js变量
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, "*");