JavaScript iFrame 안의 객체 선택하기

JavaScript에서 iframe 내부의 DOM 요소에 접근하는 방법입니다.

기본 방법

// iframe 내부 body의 innerHTML
window.frames["se2_iframe"].document.body.innerHTML;

// 또는 contentWindow 사용
document.getElementById("se2_iframe").contentWindow.document.body.innerHTML;

다양한 접근 방법

// 방법 1: name 속성으로 접근
var iframeDoc = window.frames["iframeName"].document;

// 방법 2: ID로 접근
var iframe = document.getElementById("myIframe");
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

// 방법 3: contentWindow 사용
var iframeWindow = document.getElementById("myIframe").contentWindow;
var iframeDoc = iframeWindow.document;

// 방법 4: jQuery 사용
var iframeContents = $("#myIframe").contents();
var element = iframeContents.find("#targetElement");

iframe 내부 요소 조작

// 특정 요소 선택
var iframe = document.getElementById("myIframe");
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
var element = iframeDoc.getElementById("someElement");

// 스타일 변경
element.style.backgroundColor = "yellow";

// 값 가져오기
var value = iframeDoc.querySelector("input[name=username]").value;

// 이벤트 바인딩
iframeDoc.getElementById("btn").onclick = function() {
    alert("클릭!");
};

부모 창에서 iframe 접근

// iframe의 전역 변수 접근
var iframeVar = document.getElementById("myIframe").contentWindow.myVariable;

// iframe의 함수 호출
document.getElementById("myIframe").contentWindow.myFunction();

iframe에서 부모 창 접근

// 부모 창 document
parent.document.getElementById("parentElement");

// 부모 창 함수 호출
parent.parentFunction();

// 최상위 창 접근
top.document.body;

로드 완료 후 접근

var iframe = document.getElementById("myIframe");
iframe.onload = function() {
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    console.log(doc.body.innerHTML);
};

// jQuery 방식
$("#myIframe").on("load", function() {
    var contents = $(this).contents();
    console.log(contents.find("body").html());
});

주의사항

  • 동일 출처 정책(Same-Origin Policy)으로 인해 다른 도메인의 iframe 내용에는 접근 불가
  • CORS 설정이 필요한 경우 서버측 헤더 설정 필요
  • iframe이 완전히 로드된 후에 접근해야 함