Angular2+ iframe跨域調用父頁面js


業務場景:列表頁面添加一個導入功能,該導入功能由第三方頁面提供,導入完成后需要通知主列表刷新數據。

先來看看iframe跨域調用父頁面的實現邏輯(以postMessage方式為例)

 (postMessage介紹:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage )

1.父頁面html 

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
  window.onload = function () {
  //添加監聽事件。
  if (typeof window.addEventListener != "undefined")
    window.addEventListener("message", func, false);
  else if (typeof window.attachEvent != 'undefined')//兼容不支持addEventLinstener的IE。
    window.attachEvent("onmessage", func);
}
  //被調用的函數。
  function invocationTarget(msg) {
    if (msg)
      alert(msg);
    else
      alert("~~~");
    }
  //監聽事件回調函數。
  function func(e) {
    if (e.data.Result)
      invocationTarget(e.data.Data);
  }
</script>
</head>
<body>
  <iframe src="子頁面域名/HtmlPage.html" style="border:0px"></iframe>
</body>
</html>

 
 

 

2. 子頁面html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
  <script type="text/javascript">
    function invocation() {
      var data = { Result: true, Data: 'hello world' };
      //第一個參數表示要傳遞的參數,第二個參數表示要傳遞到的目標。
      window.parent.postMessage(data, "父頁面域名/HtmlPage.html");
    }
  </script>
</head>
<body>
  <input onclick="invocation();" type="button" />
</body>
</html>

以上邏輯是基於父頁面是html實現的,見紅色字體標注,子頁面回調給指定的窗口源。

來看看postMessage參數說明:

postMessage(data,origin)方法接受兩個參數

 1.data:要傳遞的數據,html5規范中提到該參數可以是JavaScript的任意基本類型或可復制的對象,然而並不是所有瀏覽器都做到了這點兒,部分瀏覽器只能處理字符串參數,所以我們在傳遞參數的時候需要使用JSON.stringify()方法對對象參數序列化,在低版本IE中引用json2.js可以實現類似效果。

2.origin:字符串參數,指明目標窗口的源,協議+主機+端口號[+URL],URL會被忽略,所以可以不寫,這個參數是為了安全考慮,postMessage()方法只會將message傳遞給指定窗口,當然如果願意也可以建參數設置為"*",這樣可以傳遞給任意窗口,如果要指定和當前窗口同源的話設置為"/"。

到此就出現另一個問題了:angular彈窗式組件如何通過URL反映?也就是如何把父頁面集成到組件中。

因為組件和js通訊是很好實現的,這樣我們可以設法把父頁面嵌套在組件中(iframe方式嵌套)

 

UrlIframeModalComponent組件通過Iframe嵌套IframeModal.html父頁面,IframeModal.html父頁面通過Iframe嵌套第三方子頁面 testurl/

1.UrlIframeModalComponent.html 組件(模態彈出)

<iframe width="100%" height="100%" style="overflow:auto;" frameborder="0" [src]=" /assets/IframeModal.html | safe">
</iframe>

 UrlIframeModalComponent.ts 

export class UrlIframeModalComponent implements OnInit {
 
constructor() { }
ngOnInit() {
  //添加監聽事件:監聽由 IframeModal.html發出的callBackFromIframe事件
  document.addEventListener('callBackFromIframe', this.callBack);
}
 
callBack(evt){
  //回調參數
  const param = evt.param;
  console.log(param);
}
 
ngOnDestroy() {
  document.removeEventListener("callBackFromIframe", this.callBack); //銷毀監聽,否則會多次接收
}
 
}

 

2.IframeModal.html 父頁面,與第三方子頁面及UrlIframeModalComponent組件通訊

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
  window.onload = function () {
  //添加監聽事件。
  if (typeof window.addEventListener != "undefined")
    window.addEventListener("message", func, false);
  else if (typeof window.attachEvent != 'undefined') //兼容不支持addEventLinstener的IE。
    window.attachEvent("onmessage", func);
  }
  //被調用的函數。
  function invocationTarget(param) {
    //接收到子頁面消息后,通知組件
    var evt = document.createEvent("HTMLEvents");
    evt.param = param;
    evt.initEvent("callBackFromIframe", false, false);
    parent.window.document.dispatchEvent(evt);
  }
  //監聽事件回調函數。
  function func(e) {
    if (e.data.Result == true)
      invocationTarget(e.data);
}

</script>
</head>

<body>
<iframe src="http://.../第三方子頁面.html" style="border:0px"></iframe>
</body>

</html>

3.第三方子頁面 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="css/default.css" type="text/css" rel="stylesheet">
</head>
<body>
    <div id="mainDiv">
        <div id="content">
            這是第三方頁面功能...
            (導入文件功能)
            <br />
            <br />
            <a style="color:blue; cursor: pointer;" onclick="notifyBack('導入完成')">導入完成</a>
            <a style="color:blue; cursor: pointer;" onclick="notifyBack('取消')">取消</a>
        </div>
    </div>
    <script type="text/javascript">
        function notifyBack(msg) {
            var data = {
                Result: true,
                Data: msg
            };
            //第一個參數表示要傳遞的參數,第二個參數表示要傳遞到的目標。
            window.parent.postMessage(data, "http://localhost:4200/assets/IframeModal.html");
        }
    </script>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM