Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách gọi hàm cửa sổ cha từ iframe bằng JavaScript

Sử dụng window.top hoặc window.parent

  • window.top – cửa sổ gốc nhất (top-level).
  • window.parent – cửa sổ cha trực tiếp (có thể khác top nếu iframe lồng nhau).

Ví dụ

Trang cha (parent.html):

<!DOCTYPE html>
<html>
<body>
  <script>
    function parentFunction() {
      alert("Được gọi từ iframe!");
    }
  </script>
  <iframe src="child.html" id="myFrame"></iframe>
</body>
</html>

Trang con (child.html):

<!DOCTYPE html>
<html>
<body>
  <button onclick="callParent()">Gọi hàm cha</button>
  <script>
    function callParent() {
      // Kiểm tra cùng origin (CORS)
      if (window.top && window.top.parentFunction) {
        window.top.parentFunction();
      }
    }
  </script>
</body>
</html>

Quan trọng: Chính sách cùng nguồn (Same-Origin Policy)

Chỉ hoạt động khi trang cha và con cùng domain, port, protocol. Nếu khác nguồn, dùng postMessage():

// Trong iframe (con)
window.parent.postMessage({type: "CALL_FUNC", name: "parentFunction"}, "https://parent-domain.com");

// Trong trang cha
window.addEventListener("message", (e) => {
  if (e.origin !== "https://child-domain.com") return;
  if (e.data.type === "CALL_FUNC" && window[e.data.name]) {
    window[e.data.name]();
  }
});