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

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

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

然而,这似乎不起作用。一点检查显示,帧['nameOfMyIframe']中的变量未定义,除非等待一段时间加载iframe。然而,当iframe加载时,变量是不可访问的(我得到了拒绝权限的类型错误)。

有人知道这方面的工作吗?


当前回答

我觉得这样更干净:

var $iframe = $("#iframeID").contents();
$iframe.find('selector');

其他回答

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

iframe_page.php

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

    $domain = file_get_contents($URL);

    echo $domain;
?>

然后是这样的:

显示页面.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编辑外部页面而不拒绝访问等的示例。。。

Use

iframe.contentWindow.document

而不是

iframe.contentDocument

此解决方案的工作原理与iFrame相同。我已经创建了一个PHP脚本,可以从其他网站获取所有内容,最重要的是,您可以轻松地将自定义jQuery应用于外部内容。请参考以下脚本,该脚本可以从其他网站获取所有内容,然后您也可以应用您的cusom 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;
}

要获得更高的鲁棒性:

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;
}

and

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

if (frame_win) {
  $(frame_win.contentDocument || frame_win.document).find('some selector').doStuff();
  ...
}
...

我认为你所做的一切都要遵守同一原产地政策。这应该是您收到拒绝权限类型错误的原因。