835

我想使用 jQuery 在 iframe 中操作 HTML。

我想我可以通过将 jQuery 函数的上下文设置为 iframe 的文档来做到这一点,例如:

$(function(){ //document ready
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
});

但是,这似乎不起作用。一些检查表明,除非我等待 iframe 加载,否则其中的变量frames['nameOfMyIframe']是。undefined但是,当 iframe 加载时,变量不可访问(我得到permission denied-type 错误)。

有谁知道解决这个问题的方法?

4

15 回答 15

1017

如果<iframe>来自同一域,则可以轻松访问元素

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

参考

于 2009-10-28T18:54:19.867 回答
400

我认为您所做的是受同源政策的约束。这应该是您收到权限被拒绝类型错误的原因。

于 2008-12-13T08:25:40.263 回答
96

你可以使用.contents()jQuery的方法。

如果 iframe 与主页位于同一域中,则该.contents()方法还可用于获取 iframe 的内容文档。

$(document).ready(function(){
    $('#frameID').load(function(){
        $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');
    });
});
于 2010-04-02T18:27:46.360 回答
48

如果 iframe src 来自另一个域,您仍然可以这样做。您需要将外部页面读入 PHP 并从您的域中回显它。像这样:

iframe_page.php

<?php
    $URL = "http://external.com";

    $domain = file_get_contents($URL);

    echo $domain;
?>

然后是这样的:

display_page.html

<html>
<head>
  <title>Test</title>
 </head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script>

$(document).ready(function(){   
    cleanit = setInterval ( "cleaning()", 500 );
});

function cleaning(){
    if($('#frametest').contents().find('.selector').html() == "somthing"){
        clearInterval(cleanit);
        $('#selector').contents().find('.Link').html('ideate tech');
    }
}

</script>

<body>
<iframe name="frametest" id="frametest" src="http://yourdomain.com/iframe_page.php" ></iframe>
</body>
</html>

以上是如何通过 iframe 编辑外部页面而不拒绝访问等的示例...

于 2010-06-27T10:15:18.890 回答
34

采用

iframe.contentWindow.document

代替

iframe.contentDocument
于 2010-12-02T10:20:33.573 回答
33

我发现这种方式更清洁:

var $iframe = $("#iframeID").contents();
$iframe.find('selector');
于 2012-08-03T19:17:51.690 回答
27

您需要将事件附加到 iframe 的 onload 处理程序,并在其中执行 js,以便确保 iframe 在访问之前已完成加载。

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

以上将解决“尚未加载”的问题,但关于权限,如果您在 iframe 中加载来自不同域的页面,由于安全限制,您将无法访问它。

于 2008-12-13T08:11:29.683 回答
22

您可以使用 window.postMessage 在页面和他的 iframe 之间调用一个函数(跨域与否)。

文档

page.html

<!DOCTYPE html>
<html>
<head>
    <title>Page with an iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'page',
        variable:'This is the page.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    function iframeReady(iframe) {
        if(iframe.contentWindow.postMessage) {
            iframe.contentWindow.postMessage('Hello ' + Page.id, '*');
        }
    }
    </script>
</head>
<body>
    <h1>Page with an iframe</h1>
    <iframe src="iframe.html" onload="iframeReady(this);"></iframe>
</body>
</html>

iframe.html

<!DOCTYPE html>
<html>
<head>
    <title>iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'iframe',
        variable:'The iframe.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    $(window).on('load', function() {
        if(window.parent.postMessage) {
            window.parent.postMessage('Hello ' + Page.id, '*');
        }
    });
    </script>
</head>
<body>
    <h1>iframe</h1>
    <p>It's the iframe.</p>
</body>
</html>
于 2014-02-02T14:34:25.387 回答
4

我更喜欢使用其他变体进行访问。您可以从父级访问子 iframe 中的变量。 $也是一个变量,您可以访问它的刚刚调用 window.iframe_id.$

例如window.view.$('div').hide()- 隐藏 iframe 中 ID 为“view”的所有 div

但是,它在 FF 中不起作用。为了更好的兼容性,您应该使用

$('#iframe_id')[0].contentWindow.$

于 2012-09-02T15:21:04.603 回答
2

您是否尝试过经典的,使用 jQuery 的内置准备功能等待加载完成?

$(document).ready(function() {
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
} );

ķ

于 2008-12-13T08:06:29.930 回答
2

我创建了一个示例代码。现在您可以轻松地从不同的域了解您无法访问 iframe 的内容 .. 相同的域我们可以访问 iframe 内容

我与您分享我的代码,请运行此代码检查控制台。我在控制台打印图像 src。有四个 iframe,两个 iframe 来自同一域,另外两个来自其他域(第三方)。您可以看到两个图像 src(https://www.google.com/logos/doodles/2015/googles-new-logo -5078286822539264.3-hp2x.gif

https://www.google.com/logos/doodles/2015/arbor-day-2015-brazil-5154560611975168-hp2x.gif )在控制台,也可以看到两个权限错误(2错误:权限被拒绝访问属性'文档'

...irstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument...

) 来自第三方 iframe。

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<p>iframe from same domain</p>
  <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="iframe.html" name="imgbox" class="iView">

</iframe>
<p>iframe from same domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
   src="iframe2.html" name="imgbox" class="iView1">

</iframe>
<p>iframe from different  domain</p>
 <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif" name="imgbox" class="iView2">

</iframe>

<p>iframe from different  domain</p>
 <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="http://d1rmo5dfr7fx8e.cloudfront.net/" name="imgbox" class="iView3">

</iframe>

<script type='text/javascript'>


$(document).ready(function(){
    setTimeout(function(){


        var src = $('.iView').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 2000);


    setTimeout(function(){


        var src = $('.iView1').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 3000);


    setTimeout(function(){


        var src = $('.iView2').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 3000);

         setTimeout(function(){


        var src = $('.iView3').contents().find("img").attr('src');
    console.log(src);
         }, 3000);


    })


</script>
</body>
于 2015-09-24T09:29:04.870 回答
1

为了更加稳健:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

...
var frame_win = getIframeWindow( frames['nameOfMyIframe'] );

if (frame_win) {
  $(frame_win.contentDocument || frame_win.document).find('some selector').doStuff();
  ...
}
...
于 2018-10-31T21:50:22.960 回答
1

我最终在这里寻找没有 jquery 的 iframe 的内容,所以对于其他寻找它的人来说,就是这样:

document.querySelector('iframe[name=iframename]').contentDocument
于 2018-12-30T23:42:00.290 回答
1

此解决方案与 iFrame 相同。我创建了一个 PHP 脚本,可以从其他网站获取所有内容,最重要的是您可以轻松地将自定义 jQuery 应用于该外部内容。请参考以下脚本,该脚本可以从其他网站获取所有内容,然后您也可以应用您的自定义 jQuery/JS。此内容可以在任何地方、任何元素或任何页面内使用。

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
  Function to display frame from another domain 
*/

function displayFrame()
{
  $webUrl = 'http://[external-web-domain.com]/';

  //Get HTML from the URL
  $content = file_get_contents($webUrl);

  //Add custom JS to returned HTML content
  $customJS = "
  <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
    //Hide Navigation bar
    jQuery(\".navbar.navbar-default\").hide();

  </script>";

  //Append Custom JS with HTML
  $html = $content . $customJS;

  //Return customized HTML
  return $html;
}
于 2019-01-15T11:06:28.507 回答
0

如果下面的代码不起作用

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

这是使其工作的可靠方法:

$(document).ready(function(){ 
  setTimeout(
    function () {
      $("#iFrame").contents().find("#someDiv").removeClass("hidden");
    },
    300
  );
});

这样脚本将在 300 毫秒后运行,因此它将获得足够的时间iFrame来加载,然后代码将开始执行。有时iFrame不会加载并且脚本会尝试在它之前执行。300ms可以根据您的需要调整为其他任何内容。

于 2021-11-12T15:42:01.363 回答