0 투표
(120 포인트)
$("#FrameId")[0].contentWindow.subFunction();

// or, 만약 jQuery 사용하지 않을 경우
document.getElementById("FrameId").contentWindow.subFunction();

1 답변

0 투표

가능합니다. 다만 같은 도메인(동일 출처, same-origin) 인지에 따라 방법/제한이 달라집니다.


✅ 1) 같은 도메인(같은 출처)일 때: iframe 내부 함수 호출

const frame = document.getElementById("FrameId");
frame.contentWindow.subFunction();

jQuery면:

$("#FrameId")[0].contentWindow.subFunction();

⚠️ iframe이 로드된 뒤에 호출해야 합니다.

const frame = document.getElementById("FrameId");
frame.addEventListener("load", () => {
  frame.contentWindow.subFunction();
});

❌ 2) 다른 도메인(교차 출처)일 때: 직접 호출 불가

보안 정책 때문에 아래처럼 contentWindow바로 함수 호출이 막힙니다.
이 경우에는 postMessage 방식으로 통신해야 합니다.

(부모 → iframe)

const frame = document.getElementById("FrameId");
frame.contentWindow.postMessage({ type: "CALL_SUB_FUNCTION", payload: {} }, "https://iframe-domain.com");

(iframe 쪽에서 수신)

window.addEventListener("message", (event) => {
  if (event.origin !== "https://parent-domain.com") return;

  if (event.data?.type === "CALL_SUB_FUNCTION") {
    subFunction();
  }
});

✔️ 정리

  • 같은 도메인contentWindow.subFunction() 가능
  • 다른 도메인 → 직접 호출 불가 → postMessage로 요청/응답 구현 필요
구로역 맛집 시흥동 맛집
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
...