iframe 后退 浏览器history 问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Aimee1608/article/details/81291169

问题

浏览器机制的原因,在iframe导航变化后手动点击浏览器的后退按钮也依然只是后退iframe中的导航

只想让父页面后退,并不想让iframe 后退,但在改变了iframe 的src 后就达不到这样的效果

解决

不要修改iframe.src,而是删除旧iframe元素,新建一个iframe元素并替换它,这样不会产生history。
直接createElement,替换原来的iframe。

案例

父页面 iframe.html

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <meta name="renderer" content="webkit">
        <title></title>
    </head>
    <body>
        <h1>父页面</h1>
        <button id="openBtn">打开iframe</button>
        <div id="h5SourceShow" style="display:none">
          <iframe id="iframe" src="" width="300" height="400"></iframe>
        </div>
    </body>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(function(){
      $('#openBtn').click(function(){
        $('#iframe').attr('src', 'iframe-demo.html')
          $('#h5SourceShow').css('display','block')
      })
      window.addEventListener('message', function (e) {
          console.log(e);
          if (e.data.type == 'coursewareH5Close') {
              coursewareH5Close();
          }else{

          }
      }, false);
    })
  function coursewareH5Close(){
     var iframe = '<iframe id="iframe" src="" width="300" height="400"></iframe>'
     $('#iframe').remove()
      $('#h5SourceShow').css('display','none').html(iframe)
  }
    </script>
</html>

嵌套的子页面 iframe-demo.html

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <meta name="renderer" content="webkit">
        <title></title>
    </head>
    <body style="background:pink">
        <h2>子页面</h2>
        <button id="closeBtn">关闭iframe</button>
    </body>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(function(){
      $('#closeBtn').click(function(){
        var e = {
                type: "coursewareH5Close"
            };
            window.parent.postMessage(e, "*"),
            console.log("postMessage:", e)
      })
    })
    </script>
</html>

通过打开按钮打开 iframe,然后使用iframe 里面的关闭按钮,给父页面传递message,关闭当前的iframe,直接移除当前的iframe,创建新的iframe。

猜你喜欢

转载自blog.csdn.net/Aimee1608/article/details/81291169