方法window.top.postMessage重定向到初始页

时间:2019-05-23 11:41:25

标签: javascript iframe postmessage

嗨,我在iframe中有两个页面(index.html,another-one.html)。 index.html有一个重定向到another-one.html的按钮  另一个one.html使用window.top.postMessage发送了邮件,导致其重定向回初始邮件。

  1. index.html(最初加载页面)
  2. another-page.html。
  3. 从other-page.html触发window.top.postMessage
  4. 已重定向到初始页面。

预计应保留在index.html

装有index.html的主机页面或容器页面

主机页面代码

  <iframe src ="http://127.0.0.1:8888/index.html" name="example" id="example" application="yes">
    </iframe>

主机页面中的js代码

window.addEventListener("message", (e)=>{
  if(e && e.data){
    this.pagedata  = e.data;
  }
}, false);

index.html的代码

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TEST1</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
  <script type="text/javascript">
    $(document).ready(()=>{
        $("#redirectButton").click(()=>{
            window.location.href="./another-page.html";
        });
    })
  </script>
</head>
<body >
    <button id="redirectButton" type="button">Redirect</button>
</body>
</html>

another-page.html的代码

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>New Page</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
  <script type="text/javascript">
    $(document).ready(()=>{
        $("#btnMessage").click(()=>{
            let obj = {
                message:"this is new message"+(new Date())
            };
            window.top.postMessage(obj, '*');
        });
    })
  </script>
</head>
<body >
    Another Page
    <input id="btnMessage" type="button" value="Send Again"></input>
</body>
</html>

0 个答案:

没有答案