Skip to content
Advertisement

PostMessage Issues Using IFrame in JS

I have two buttons that work differently. The first one is when you click the reload button, it should reload the page. The second one is when you click it, it will show the alert on the page. I’m using postMessage because its inside the iframe. I’m not sure why the two buttons are not working but I already implemented the postMessage and window.onmessage

CODESANDBOX

  1. PARENT WINDOW

  2. CHILD PAGE

CODE

function reloadPage() {
  window.parent.postMessage({ reload: true }, 'https://8beu4h.csb.app');
}

function alertPage() {
  window.parent.postMessage({ alert: true }, 'https://8beu4h.csb.app');
}

    window.onmessage = (event) => {
      const { data, origin, source } = event;
      if (source == frameToListen.contentWindow) {
        try {
          if (data.reload) {
            window.location.reload();
          }
        } catch (e) {
          console.error(e);
        }
      }
    };
    window.onmessage = (event) => {
      const { data, origin, source } = event;
      if (source == frameToListen.contentWindow) {
        try {
          if (data.alert) {
            alert("HI");
          }
        } catch (e) {
          console.error(e);
        }
      }
    };

Advertisement

Answer

Parent Window

window.addEventListener(
  "message",
  function (event) {
    const { data, source } = event;
    console.log(source);
    if (source == frameToListen.contentWindow) {
      if (data.reload) window.location.reload();
      if (data.alert) alert("HI");
    }
  },
  false
);

CHILD WINDOW

function reloadPage() {
  window.parent.postMessage({ reload: true }, 'https://eq0o2y.csb.app/');
}

function alertPage() {
  window.parent.postMessage({ alert: true }, 'https://eq0o2y.csb.app/');
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement