Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chrish@diversifiedtechnology.com's avatar

Iframe changes to router push

I have a hosted page an iframe that has a submit button on it. This is externally hosted and not mine I have no access to it. I need to be able to read when the iframe changes or submits and push to a new page based on this result. The result will be an error or success. I send html to it via s return url but have no luck getting that back to Vue to push the router to a new page

0 likes
2 replies
LaryAI's avatar
Level 58

One possible solution to this problem is to use the postMessage API to communicate between the iframe and the parent window. Here's how you can implement it in Vue.js:

  1. In your Vue component, create a method to handle the message received from the iframe:
methods: {
  handleMessage(event) {
    // Check if the message is coming from the iframe
    if (event.source === iframe.contentWindow) {
      // Get the message data
      const message = event.data;

      // Check if the message indicates success or error
      if (message === 'success') {
        // Push to a new page for success
        this.$router.push('/success');
      } else if (message === 'error') {
        // Push to a new page for error
        this.$router.push('/error');
      }
    }
  }
}
  1. Add an event listener for the message event in the mounted lifecycle hook of your Vue component:
mounted() {
  window.addEventListener('message', this.handleMessage);
}
  1. In the template of your Vue component, add an iframe element with a ref attribute to access it in the component:
<template>
  <div>
    <!-- Your other content here -->

    <iframe ref="myIframe" src="https://example.com"></iframe>
  </div>
</template>
  1. In the mounted lifecycle hook, get a reference to the iframe and add a listener for the load event to send a message to the iframe:
mounted() {
  const iframe = this.$refs.myIframe;

  iframe.addEventListener('load', () => {
    // Send a message to the iframe
    iframe.contentWindow.postMessage('Hello from parent', '*');
  });

  window.addEventListener('message', this.handleMessage);
}

Make sure to replace 'https://example.com' with the actual URL of the external page you want to load in the iframe.

This solution assumes that the external page in the iframe is on the same domain as your Vue application. If it's on a different domain, you'll need to handle cross-origin communication by setting the appropriate X-Frame-Options or Content-Security-Policy headers on the external page.

Please or to participate in this conversation.