iframe中的网站不在同一个域中,但都是我的,我想在iframe和父站点之间进行通信。这可能吗?
当前回答
使用event.source.window.postMessage发送回发送方。
从Iframe
window.top.postMessage('I am Iframe', '*')
window.onmessage = (event) => {
if (event.data === 'GOT_YOU_IFRAME') {
console.log('Parent received successfully.')
}
}
然后从父母那里说回来。
window.onmessage = (event) => {
event.source.window.postMessage('GOT_YOU_IFRAME', '*')
}
其他回答
窗外。顶级物业应该能满足你的需要。
如。
alert(top.location.href)
看到 http://cross-browser.com/talk/inter-frame_comm.html
你也可以使用
postMessage消息(,' * ');
在花了2天时间试图获得一个iFrame发布消息回父,一个Vue应用程序在我的情况下,我遇到了这个优秀的参考:
https://dev-bay.com/iframe-and-parent-window-postmessage-communication/
从iframe到parent:
const parentWindow = window.parent;
class Message {
constructor(type, body) {
this.type = type;
this.body = body;
}
};
function sendMessage (windowObj, payload) {
if(windowObj) {
windowObj.postMessage(payload, "*");
}
};
//Then call appropriately:
sendMessage(parentWindow, new Message("button-click", "Show Stats Overlay"));
在父文件中,我的Vue应用程序挂载了生命周期事件,但请参考您自己的需求链接:
window.addEventListener("message", (e) => {
var data = e.data;
console.log("RECEIVED message from CHILD TO PARENT", data);
var type = data.type;
var body = data.body;
if(type === "button-click" && body) {
console.log("button-click RECEIVED FROM CHILD")
//Additional functionality ...
} else if (type === "text-msg" && body) {
console.log("TEXT MESSAGE RECEIVED FROM CHILD");
//Additional functionality ...
}
});
请参阅从父节点到iFrame的通信示例。
希望这能帮助到其他人。
使用event.source.window.postMessage发送回发送方。
从Iframe
window.top.postMessage('I am Iframe', '*')
window.onmessage = (event) => {
if (event.data === 'GOT_YOU_IFRAME') {
console.log('Parent received successfully.')
}
}
然后从父母那里说回来。
window.onmessage = (event) => {
event.source.window.postMessage('GOT_YOU_IFRAME', '*')
}
对于不同的域,不可能直接调用方法或访问iframe的内容文档。
您必须使用跨文档消息传递。
Parent -> iframe
例如在顶部窗口:
myIframe.contentWindow.postMessage('hello', '*');
在iframe中:
window.onmessage = function(e) {
if (e.data == 'hello') {
alert('It works!');
}
};
Iframe ->父级
例如在顶部窗口:
window.onmessage = function(e) {
if (e.data == 'hello') {
alert('It works!');
}
};
在iframe中:
window.top.postMessage('hello', '*')
推荐文章
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 我如何在网站上使用谷歌的Roboto字体?
- 父ng-repeat从子ng-repeat的访问索引
- 如何禁用文本区域大小调整?
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 保留HTML字体大小时,iPhone的方向从纵向改变为横向
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;