programing

JavaScript/jQuery를 사용하여 iframe의 내용에 액세스하려면 어떻게 해야 합니까?

itsource 2022. 10. 5. 23:32
반응형

JavaScript/jQuery를 사용하여 iframe의 내용에 액세스하려면 어떻게 해야 합니까?

jQuery를 사용하여 iframe 내의 HTML을 조작하고 싶습니다.

jQuery 함수의 콘텍스트를 iframe의 문서로 설정하면 다음과 같이 할 수 있다고 생각했습니다.

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

을 사용하다, 에 있는 frames['nameOfMyIframe']undefined되는 것을 잠시 않는 한.iframe은 로드되지 않습니다.수 I get 、 iframe 로( ((( ( I get 、 iframe ) 。permission denied-type errors).

이 문제에 대한 해결 방법을 아는 사람이 있습니까?

경우,<iframe> 같은 으로부터, 할 수 .

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

언급

당신이 하고 있는 것은 같은 원산지 정책의 대상이라고 생각합니다.이것이 permission denied type 오류가 발생하는 이유입니다.

jQuery 메서드를 사용할 수 있습니다.

.contents()와 같은 .iframe은 iframe과 같은 도메인에 있습니다.

$(document).ready(function(){
    $('#frameID').load(function(){
        $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');
    });
});

iframe src가 다른 도메인에서 온 경우에도 가능합니다.외부 페이지를 PHP로 읽고 도메인에서 에코해야 합니다.다음과 같이 합니다.

iframe_page 입니다.php

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

    $domain = file_get_contents($URL);

    echo $domain;
?>

그 다음에 이렇게.

display_page.display

<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을 통해 외부 페이지를 편집하는 방법입니다.

사용하다

iframe.contentWindow.document

대신

iframe.contentDocument

이 방법이 더 깨끗하다고 생각합니다.

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

iframe의 온로드 핸들러에 이벤트를 부가하고 거기에서 js를 실행해야 iframe에 액세스하기 전에 로드가 완료되었는지 확인할 수 있습니다.

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

위의 '아직 로드되지 않은' 문제는 해결되지만 권한과 관련하여 다른 도메인에서 페이지를 로드하는 경우 보안 제한으로 인해 액세스할 수 없습니다.

window.postMessage를 사용하여 페이지와 iframe 사이의 함수를 호출할 수 있습니다(도메인 간 여부에 관계없이).

문서

page.displaces를 클릭합니다.

<!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.syslog

<!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>

액세스에는 다른 변종을 사용하는 것을 선호합니다.iframe을 사용하다 $이기도 하고, 그인 「콜」, 「콜」에의 할 수 있습니다.window.iframe_id.$

를 들어, 「」라고 하는 것은,window.view.$('div').hide()가 ' 'view'인의 모든

근데 FF에서는 안 돼요.호환성을 향상시키려면

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

jQuery의 내장 Ready 기능을 사용하여 로드가 완료될 때까지 기다리는 클래식 버전을 사용해 보셨습니까?

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

K

샘플 코드를 만듭니다.이제 당신은 iframe의 콘텐츠에 접근할 수 없다는 것을 다른 도메인에서 쉽게 이해할 수 있습니다.iframe 콘텐츠에 액세스할 수 있는 도메인과 동일

코드를 공유합니다.콘솔에서 이 코드를 실행하세요.콘솔에서 이미지 src를 인쇄합니다.를 인쇄합니다.iframe은 4개, iframe은 같은 도메인에서2개, 다른 도메인(서드파티)에서2개입니다.2개의 이미지 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개의 권한 오류(2 오류: 속성 'message'에 액세스하기 위한 권한이 거부됨)가 표시됩니다.

...irstChild)}, 내용: function(a){return m.nodeName(a, iframe)?a.내용...

)는, 서드 파티의 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>

한층 더 견고함을 실현하기 위해서:

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();
  ...
}
...

iframe의 내용을 jquery 없이 입수할 수 있는 방법을 찾고 있었습니다.따라서, 그것을 찾고 있는 다른 사람에게는, 다음과 같습니다.

document.querySelector('iframe[name=iframename]').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;
}

아래 코드가 작동하지 않는 경우

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

이 기능을 실현하는 신뢰성 높은 방법은 다음과 같습니다.

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

이렇게 하면 스크립트는 300밀리초 후에 실행되므로 충분한 시간을 확보할 수 있습니다.iFrame로딩되면 코드가 작동하게 됩니다.경우에 따라서는iFrame로딩되지 않고 스크립트는 그 전에 실행하려고 합니다. 300ms니즈에 따라 다른 모든 것을 조정할 수 있습니다.

언급URL : https://stackoverflow.com/questions/364952/how-can-i-access-the-contents-of-an-iframe-with-javascript-jquery

반응형