development

jQuery / JavaScript : iframe 콘텐츠 액세스

big-blog 2020. 9. 29. 08:05
반응형

jQuery / JavaScript : iframe 콘텐츠 액세스


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

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

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

그러나 이것은 작동하지 않는 것 같습니다. 에서 변수가 검사 쇼 날의 비트 frames['nameOfMyIframe']입니다 undefined내가 부하에 iframe을 위해 잠시 기다려하지 않는. 그러나 iframe이로드되면 변수에 액세스 할 수 없습니다 ( permission denied유형 오류가 발생 함).

누구든지 이것에 대한 해결 방법을 알고 있습니까?


나는 당신이하는 일이 동일한 원산지 정책의 적용을받는다고 생각합니다 . 이것이 권한 거부 유형 오류가 발생 하는 이유 입니다.


<iframe>동일한 도메인에있는 경우 다음 과 같이 요소에 쉽게 액세스 할 수 있습니다.

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

참고


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


이 방법이 더 깨끗합니다.

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

사용하다

iframe.contentWindow.document

대신에

iframe.contentDocument

이벤트를 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에서 페이지를로드하는 경우 보안 제한으로 인해 액세스 할 수 없습니다.


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>

액세스를 위해 다른 변형을 사용하는 것을 선호합니다. 부모에서 자식 iframe의 변수에 액세스 할 수 있습니다. $변수이기도하며 호출에 대한 액세스를받을 수 있습니다.window.iframe_id.$

예 : window.view.$('div').hide()-ID가 'view'인 iframe의 모든 div를 숨 깁니다.

그러나 FF에서는 작동하지 않습니다. 더 나은 호환성을 위해 다음을 사용해야합니다.

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


jQuery의 내장 준비 기능을 사용하여로드가 완료되기를 기다리면서 클래식을 시도해 보셨습니까?

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

케이


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

내 코드를 공유합니다.이 코드를 실행하여 콘솔을 확인하십시오. 콘솔에서 이미지 src를 인쇄합니다. 4 개의 iframe, 동일한 도메인에서 오는 2 개의 iframe 및 다른 도메인 (타사)에서 오는 2 개의 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>

나는 여기에서 jquery없이 iframe의 내용을 얻기 위해 끝났으므로 그것을 찾는 다른 사람에게는 다음과 같습니다.

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

더욱 견고 함을 위해 :

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

참고 URL : https://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe

반응형