>웹 프론트엔드 >JS 튜토리얼 >iFrame 내부의 요소에 액세스하는 방법은 무엇입니까?

iFrame 내부의 요소에 액세스하는 방법은 무엇입니까?

DDD
DDD원래의
2024-12-13 21:24:18318검색

How to Access Elements Inside an iFrame?

iFrame 내의 요소에 액세스

콘텐츠를 조작하거나 포함된 프레임에서 데이터를 수집하려면 iFrame 내에서 요소를 검색해야 할 수 있습니다. 방법은 다음과 같습니다.

방법:

iFrame 내에서 DIV 요소를 가져오려면 다음 코드를 사용하세요.

var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;

또는 더 간단히 말하면:

var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

innerDoc을 얻은 후에는 다음을 사용하여 해당 ID로 DIV 요소에 액세스할 수 있습니다.

innerDoc.getElementById('divId');

참고:

iFrame이 상위 페이지와 동일한 도메인에 있는지 확인하는 것이 중요합니다. 해당 콘텐츠에 액세스할 수 있습니다. 동일 출처 정책으로 크로스 사이트 스크립팅을 방지합니다.

참고 자료:

  • MDN: [