vue嵌套iframe踩坑

判断页面是否被iframe嵌套

if (window !== window.parent) {
	// 在iframe里
	// 向父页面发送信息
	window.parent.postMessage({
		data: {
			code:"success"
		}
	}, '*');
} else {
	// toDo()
}

iframe修改src不触发刷新

在vue中通过v-bind绑定src

<iframe
	sandbox="allow-same-origin allow-scripts allow-forms"
	ref="iframe_page"
	:src="pageSrc"
	style="display:block"
	width="100%" height="858px"></iframe>

当src为已经加载过的路径时,iframe里的内容就不会刷新
通过在src后面追加时间戳来解决

	// 添加时间戳,防止iframe缓存导致的不刷新问题
	let iframeTimestamp = new Date().getTime()
	this.pageSrc = `${data.openUrl}&iframeTimestamp=${iframeTimestamp}`

使用postMessage通信

  • 在iframe向父页面传值时,还是出现了跨域问题
    发现跨域是因为在子页面里使用了top.location作为判断条件,浏览器似乎不允许使用top.location,避免使用top.location就可以解决跨域问题了
posted @ 2023-05-16 17:29  葱花粉丝  阅读(557)  评论(0)    收藏  举报