javascript - iframe 中的当前页面重复 : iframe wont load

标签 javascript jquery iframe

我正在尝试在 iframe 中复制当前页面(以演示页面在移动屏幕上的外观)。但该页面无法在 iframe 中加载 - 它只是空白。知道我的代码有什么问题吗?

$(document).ready(function(){

    var iframe = $('#my-iframe', window.parent.document);

    // if already in iframe
    if (iframe.length > 0) {
        $('<p>I\'m in an iframe!</p>').appendTo($('body'));

        // Now I can preview the website in mobile view!

        return;
    }
    else {
    	$('<iframe>', {
           src: window.location.href,
           id:  'my-iframe',
           scrolling: 'no'
        }).appendTo($('body')).load();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>The below iframe should contain this page aswell</p>

编辑:在 Firefox 上运行本地 html 文件时的结果屏幕截图; enter image description here

最佳答案

浏览器在访问 iframe 父级文档时确实很挑剔。查看是否位于 iframe 中的一种更简单的方法是仅检查父级是否存在:

$(document).ready(function(){
  // if already in iframe
  if (window.parent && window.parent !== window) {
    $('<p>I\'m in an iframe!</p>').appendTo($('body'));
    return;
  } else {
    $('<iframe>', {
      src: window.location.href,
      id:  'my-iframe',
      scrolling: 'no'
    }).appendTo($('body')).load();
  }
});

关于javascript - iframe 中的当前页面重复 : iframe wont load,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498507/

相关文章:

javascript - Three.js .png 图像呈现白色,而不是应有的样子

java - 无法获取使用 jQuery Popconfirm 插件单击的按钮的名称

javascript - 如何重现 tileView

javascript - 推迟 Trip Advisor 脚本

javascript - JSON 到多个 HTML 表

javascript - 无法在 jQuery 中突出显示具有特殊字符的单词

html - 如何在html中使用iframe?

javascript - Ajax 未加载 PHP

javascript - JS : Resize div when an iframe was clicked?

html - 更改 Joomla 布局中的列宽