PostMessage Issues Using IFrame in JS

Viewed 60

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);
        }
      }
    };
2 Answers

The second argument to Window.postMessage() is the target origin, not the source one.

Change

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

to

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

Also, onmessage can only set one handler at a time. Your second one will remove the previous one. Either you merge both handlers in a single function, either you use addEventListener()

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/');
}
Related