Contents
see List작성일 2014. 09. 25.
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이 완전히 로드된 후에 접근해야 함
javascript
| No | 작성일 | Title |
|---|---|---|
| 3384 | 2026. 08. 21. | Node.js API에서 요청 취소를 제대로 처리하는 방법: AbortSignal로 외부 작업 정리하기 |
| 3352 | 2026. 08. 13. | Node.js 응답이 간헐적으로 느릴 때: 이벤트 루프 지연 측정과 CPU 작업 분리 방법 |
| 3320 | 2026. 08. 04. | JavaScript fetch 요청을 안전하게 만드는 방법: timeout·재시도·오류 처리 실전 패턴 |
| 3288 | 2026. 07. 27. | Node.js 서버 무중단 배포를 위한 Graceful Shutdown 구현 가이드 |
| 3257 | 2026. 07. 19. | Node.js 대용량 파일 처리 가이드: 스트림과 backpressure로 메모리 사용량 제어하기 |
| 3232 | 2026. 07. 11. | Node.js 실무형 에러 처리: async/await에서 실패를 일관되게 분류하고 복구 속도 높이기 |
| 3174 | 2026. 07. 02. | Node.js 환경 변수 검증 가이드: process.env를 안전한 설정 객체로 바꾸기 |
| 3123 | 2026. 06. 24. | TypeScript 타입 좁히기 운영 가이드: unknown 입력을 안전한 도메인 객체로 바꾸기 |
| 3065 | 2026. 06. 16. | 브라우저 성능 병목 찾기: PerformanceObserver로 LCP·INP·긴 작업 로그 수집하기 |
| 2978 | 2026. 06. 08. | Node.js fetch 타임아웃과 재시도 설계: 외부 API 장애 전파 줄이기 |