最近在項目中遇到一個需求需要在一個項目中直接引用另一個項目,嘗試各種情況無果后選擇了iframe。現將調用過程中遇到的問題做一個分享。
router.go()的使用
此情況主要適用於更改iframe中src值以后導致的路由跳轉混亂。
詳細描述:當多次更改iframe->src屬性后,調用router.go(-1),不能實現路由后退上一級,而是將iframe當作一個窗口文檔,調用了該窗口文檔的window.history.go(-1),並未更改父級項目的路由后退功能。
解決辦法:
不通過改變iframe->src屬性值去訪問具體內容,采用window.location.replace(url)更改iframe將訪問的內容,具體代碼如下:
-
<!-- A.html -->
-
<template>
-
<iframe ref="iframe" scrolling="auto" width="100%" height="100%" frameborder="0" ></iframe>
-
</template>
-
<script>
-
export default {
-
name: 'ComponentsName',
-
data() {
-
return {
-
url: ''
-
}
-
},
-
watch: {
-
url(val) {
-
if (val) {
-
this.$refs.iframe.contentWindow.location.replace(val)
-
}
-
}
-
}
-
}
-
</script>
-
復制代碼
通信(父頁面和子頁面相互通信)
兩個項目之間相互通信,涉及到跨域問題,子頁面不能直接調用父頁面的方法,父頁面同樣不能調用子頁面的方法。
錯誤詳情:Error in created hook: "SecurityError: Blocked a frame with origin "http://*" from accessing a cross-origin frame."
解決辦法: postMessage
window.postMessage() 方法可以安全地實現跨源通信。該方法被調用時,會在所有頁面腳本執行完畢之后向目標窗口派發一個MessageEvent消息。代碼如下:
-
<!-- index.html -->
-
-
<html>
-
<head>
-
<title>Post Message</title>
-
</head>
-
<body>
-
<div>
-
<div id="color">Frame Color</div>
-
</div>
-
<div>
-
<iframe id="child" width="50%" src="http://172.16.110.188/test.html" height="50vw" scrolling="auto" frameborder="0"></iframe>
-
</div>
-
<script type="text/javascript">
-
window.οnlοad=function(){
-
document.getElementById('child').contentWindow.postMessage('getcolor','http://172.16.110.188');
-
}
-
window.addEventListener('message',function(e){
-
var color=e.data;
-
document.getElementById('color').style.backgroundColor=color;
-
}, false);
-
</script>
-
</body>
-
</html>
-
復制代碼
-
<!-- test.html -->
-
-
<html>
-
<head>
-
<style type="text/css">
-
html,body{
-
height:100%;
-
margin:0px;
-
}
-
#container{
-
widht:100%;
-
height:100%;
-
background-color:rgb(204, 102, 0);
-
}
-
</style>
-
</head>
-
<body style="height:100%;">
-
<div id="container" onclick="changeColor();">
-
click to change color
-
</div>
-
<script type="text/javascript">
-
var container=document.getElementById('container');
-
window.addEventListener('message',function(e){
-
if(e.source!=window.parent) return;
-
var color=container.style.backgroundColor;
-
window.parent.postMessage(color,'*');
-
}, false);
-
function changeColor () {
-
var color=container.style.backgroundColor;
-
if(color=='rgb(204, 102, 0)'){
-
color= 'rgb(204, 204, 0)';
-
} else{
-
color= 'rgb(204,102,0)';
-
}
-
container.style.backgroundColor=color;
-
window.parent.postMessage(color,'*');
-
}
-
</script>
-
</body>
-
</html>
-
復制代碼
上面的例子實現了兩個不同域的頁面之間的通信。但由於我們此處用的是動態更改iframe.contentWindow.location來訪問的內容,如果此處父頁面要向子頁面發起通信需要在iframe中頁面加載完畢以后,不然子頁面無法獲取到通信數據。
應用場景
子頁面需要調用父頁面的方法或則使用父頁面的數據時候,我們可以在子頁面向父頁面發起通信,讓父頁面調用該方法,或讓父頁面將數據傳輸過來。
注意事項
postMessage支持對象傳遞,但不是所有瀏覽器都支持對象傳遞,在使用中還是使用字符串傳值更好。
轉載於:https://juejin.im/post/5cdac2bbf265da03925804c7
https://blog.csdn.net/weixin_34033624/article/details/91446152