iframe通信


前言

微前端之iframe通信


一、iframe是什么?

可以嵌入html网页。

二、使用

属性描述
src指定要在 iframe 中显示的文档的 URL
srcdoc在 iframe 中嵌入 HTML 代码而不是外部文档
name为 iframe 定义一个名称
allow允许特定功能的列表,如 fullscreen,geolocation 等
allowfullscreen指定是否允许在 iframe 中使用全屏模式
allowpaymentrequest指定是否允许在 iframe 中进行支付请求
allowtransparency指定 iframe 是否可以是透明的
class为 iframe 定义一个或多个类名
style定义 iframe 的 CSS 样式
frameborder指定是否在 iframe 周围显示边框
width指定 iframe 的宽度
height指定 iframe 的高度
importance指定 iframe 对页面内容的重要性
loading指定 iframe 加载时的行为
referrerpolicy指定如何发送 referer HTTP 标头

三、通信

1.父页面

<body>
    <button id="button">父页面按钮</button>
    <iframe border="0" frameborder="no" height="100%" id="iframe" name="iframe" scrolling="auto" width="100%" src="http://localhost:3000/#/home" class="ng-star-inserted"></iframe>
</body>
<script>
    // 确保iframe完全加载
    window.onload = function() {
        let button = document.getElementById('button');
        let iframe_dom = document.getElementById('iframe');
        let iframe_window = iframe_dom.contentWindow; // iframe的window对象
        let iframe_document = iframe_dom.contentDocument; // iframe的document对象
        
        // 注册message事件,接收子页面消息
        window.addEventListener('message', (e) => {
            console.log('父message事件:', e.data)
        })
        // 发消息给子页面
        function sendMessage() {
			const message = '你好,我是父'; // 消息内容(可以为对象)
            const targetOrigin = '*'; // 发送到哪(URL,'*'不限制)
            iframe_window.postMessage(message, targetOrigin);
		}
		button.onclick = sendMessage;  
    };
</script>

2.子页面

<script>
	// 注册message事件,接收父页面消息
	window.addEventListener("message", function(e){
	    console.log('子message事件:', e.data)
    });
	// 发消息给父页面
	function sendMessage() {
		const message = '你好,我是父'; // 消息内容(可以为对象)
	    const targetOrigin = '*'; // 发送到哪(URL,'*'不限制)
	    window.parent.postMessage(message, targetOrigin);
	}
	sendMessage();
</script>
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值