IT

주어진 HTML로 동적으로 iframe 만들기

lottoking 2020. 7. 2. 07:29
반응형

주어진 HTML로 동적으로 iframe 만들기


JavaScript에서 iframe을 만들고 임의의 HTML로 채우려 고합니다.

var html = '<body>Foo</body>';
var iframe = document.createElement('iframe');
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);

iframe그런 다음 유효한 창과 문서가 포함될 것으로 기대 합니다. 그러나 이것은 사실이 아닙니다.

> console.log (iframe.contentWindow);
없는

직접 사용해보십시오 : http://jsfiddle.net/TrevorBurnham/9k9Pe/

내가 무엇을 간과하고 있습니까?


src새로 작성된 iframe자바 스크립트로 설정하면 요소가 문서에 삽입 될 때까지 HTML 파서가 트리거되지 않습니다. 그런 다음 HTML이 업데이트되고 HTML 파서가 호출되고 속성이 예상대로 처리됩니다.

http://jsfiddle.net/9k9Pe/2/

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);
console.log('iframe.contentWindow =', iframe.contentWindow);

또한이 답변은 일부 브라우저와의 호환성 문제가 있음을 유의하는 것이 중요합니다. 크로스 브라우저 솔루션에 대해서는 @mschr의 답변을 참조하십시오.


당신 src = encodeURI이 일해야하지만, 나는 다른 길을 갔을 것입니다 :

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

여기에는 x- 도메인 제한이없고 iframe핸들을 통해 완전히 수행되므로 나중에 프레임의 내용에 액세스하고 조작 할 수 있습니다. .write 명령이 실행되는 동안 / 이후에 (브라우저 유형에 따라) 컨텐츠가 렌더링되는지 확인해야 하지만close() 호출이 불필요하게 완료되지는 않습니다 .

콜백을 수행하는 100 % 호환 가능한 방법은 다음과 같습니다.

<html><body onload="parent.myCallbackFunc(this.window)"></body></html>

그러나 iframe에는 onload 이벤트가 있습니다. 내부 HTML을 DOM (js)으로 액세스하는 방법은 다음과 같습니다.

iframe.onload = function() {
   var div=iframe.contentWindow.document.getElementById('mydiv');
};

당신의 큰 질문에 감사드립니다. dataURI HTML 소스를 사용할 때 완전한 HTML 문서를 정의해야한다는 것을 알게되었습니다.

아래 수정 된 예를 참조하십시오.

var html = '<html><head></head><body>Foo</body></html>';
var iframe = document.createElement('iframe');
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);

<html>태그와 iframe.src문자열로 싸인 html 내용을 기록해 두십시오 .

구문 분석하려면 iframe 요소를 DOM 트리에 추가해야합니다.

document.body.appendChild(iframe);

브라우저에서 확인 iframe.contentDocument하지 않으면 검사 할 수 없습니다 disable-web-security. 당신은 메시지가 나타납니다

DOMException : 'HTMLIFrameElement'에서 'contentDocument'속성을 읽지 못했습니다 : 출처가 " http : // localhost : 7357 "인 프레임이 교차 출처 프레임에 액세스하지 못하도록 차단했습니다.


내용이 HTML 문자열 인 iframe을 만드는 대안이 있습니다 : srcdoc attribute . 이것은 오래된 브라우저 (주로 Internet Explorer 및 아마도 Safari ?)에서 지원되지 않지만 이 동작에 대한 polyfill 이 있습니다 .IE에 대한 조건부 주석을 넣거나 has.js와 같은 것을 사용하여 조건부 게으른 그것을로드하십시오.


이 작업을 수행

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

console.log(frame_win);
...

getIframeWindow 가 여기에 정의되어 있습니다.

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

참고 URL : https://stackoverflow.com/questions/10418644/creating-an-iframe-with-given-html-dynamically

반응형