sourcetip

자바스크립트로 iframe의 본문 내용을 얻는 방법은?

fileupload 2023. 7. 27. 22:13
반응형

자바스크립트로 iframe의 본문 내용을 얻는 방법은?

<iframe id="id_description_iframe" class="rte-zone" height="200" frameborder="0" title="description">
  <html>
    <head></head>
    <body class="frameBody">
      test<br/>
    </body>
  </html>
</iframe>

제가 원하는 것은 다음과 같습니다.

test<br/>

정확한 문제는 jQuery가 아닌 순수 자바스크립트로 어떻게 하느냐입니다.

하지만 저는 항상 jQuery의 소스 코드에서 찾을 수 있는 솔루션을 사용합니다.네이티브 자바스크립트의 한 줄입니다.

저에게 이것은 iframes 콘텐츠를 얻을 수 있는 가장 좋고, 읽기 쉬우며, 심지어는 가짜입니다.

먼저 당신의 iframe을 구하세요.

var iframe = document.getElementById('id_description_iframe');

// or
var iframe = document.querySelector('#id_description_iframe');

그런 다음 jQuery의 솔루션을 사용합니다.

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

그것은 심지어 인터넷 익스플로러에서 이 속임수를 하는 동안에도 작동합니다.contentWindow의 재산.iframe물건.대부분의 다른 브라우저는contentDocument이 OR 조건에서 먼저 이 속성을 증명하는 이유는 바로 속성입니다.설정되지 않은 경우 시도contentWindow.document.

iframe에서 요소 선택

그러면 보통 사용할 수 있습니다.getElementById()아니 심지어는querySelectorAll()에서 DOM-Element를 선택합니다.iframeDocument:

if (!iframeDocument) {
    throw "iframe couldn't be found in DOM.";
}

var iframeContent = iframeDocument.getElementById('frameBody');

// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');

iframe의 통화 기능

바로 사용할 수 있습니다.window에서 나온 요소.iframe일부 전역 함수, 변수 또는 전체 라이브러리(예:jQuery):

var iframeWindow = iframe.contentWindow;

// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');

// or
iframeContent = iframeWindow.$('#frameBody');

// or even use any other global variable
iframeWindow.myVar = window.myVar;

// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);

메모

이 모든 것은 동일한 출처 정책을 준수할 경우 가능합니다.

JQuery를 사용하여 다음을 시도합니다.

$("#id_description_iframe").contents().find("body").html()

그것은 나에게 완벽하게 작동합니다:

document.getElementById('iframe_id').contentWindow.document.body.innerHTML;

AFAIK, Iframe은 그런 식으로 사용될 수 없습니다.src 속성을 다른 페이지로 가리켜야 합니다.

평면 오래된 자바스크립트를 사용하여 본문 내용을 얻는 방법은 다음과 같습니다.이것은 IE와 Firefox 모두에서 작동합니다.

function getFrameContents(){
   var iFrame =  document.getElementById('id_description_iframe');
   var iFrameBody;
   if ( iFrame.contentDocument ) 
   { // FF
     iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
   }
   else if ( iFrame.contentWindow ) 
   { // IE
     iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
   }
    alert(iFrameBody.innerHTML);
 }

사용하다contentJS를 사용하는 iframe:

document.getElementById('id_iframe').contentWindow.document.write('content');

태그 사이에 텍스트를 배치하는 것은 프레임을 처리할 수 없는 브라우저를 위해 예약된 것 같습니다.

<iframe src ="html_intro.asp" width="100%" height="300">
  <p>Your browser does not support iframes.</p>
</iframe>

'src' 특성을 사용하여 iframes html...의 소스를 설정합니다.

도움이 되길 바랍니다 :)

Chalkey가 맞습니다. iframe에 포함할 페이지를 지정하려면 src 특성을 사용해야 합니다.이렇게 하고 iframe의 문서가 상위 문서와 동일한 도메인에 있는 경우 다음을 사용할 수 있습니다.

var e = document.getElementById("id_description_iframe");
if(e != null) {
   alert(e.contentWindow.document.body.innerHTML);
}

그런 다음 내용을 알림에 넣는 대신 유용한 작업을 수행할 수 있습니다.

다음 코드는 브라우저 간 호환성이 있습니다.IE7, IE8, Fx3, Safari 및 Chrome에서 작동하므로 크로스 브라우저 문제를 처리할 필요가 없습니다.IE6에서 테스트하지 않았습니다.

<iframe id="iframeId" name="iframeId">...</iframe>

<script type="text/javascript">
    var iframeDoc;
    if (window.frames && window.frames.iframeId &&
        (iframeDoc = window.frames.iframeId.document)) {
        var iframeBody = iframeDoc.body;
        var ifromContent = iframeBody.innerHTML;
    }
</script>

Javascript에서 본문 내용을 가져오기 위해 다음 코드를 사용해 보았습니다.

var frameObj = document.getElementById('id_description_iframe');

var frameContent = frameObj.contentWindow.document.body.innerHTML;

여기서 "id_description_iframe"은 iframe의 ID입니다.이 코드는 저에게 잘 작동합니다.

iframe의 본문만 선택하는 것이 아니라 일부 내용을 삽입하고 순수한 JS와 JQuery 없이 문서 없이 이 작업을 수행합니다.write(), 다른 답변이 제공하지 않는 해결책이 있습니다.

다음 단계를 사용할 수 있습니다.

1. iframe을 선택합니다.

var iframe = document.getElementById("adblock_iframe");

2. 프레임에 삽입할 요소를 만듭니다. 예를 들어, 이미지:

var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
    img.style.width = "200px";
    img.style.height = "50px";
} else {
    img.style.width = "400px";
    img.style.height = "100px";
}
img.id = "image";

3. iframe에 영상 요소를 삽입합니다.

iframe.contentWindow.document.body.appendChild(img);

iframe 본문의 내용을 코드 한 줄로 가져올 수 있습니다.

document.getElementsByTagName('iframe')[0].contentWindow.document.body.innerText;

언급URL : https://stackoverflow.com/questions/926916/how-to-get-the-bodys-content-of-an-iframe-in-javascript

반응형