Iframe Messages

Using iframes for embedding requests is a good first approach.

Iframe Event Communication

The embebed request iframe emits a postMessage event to its parent window with type: "request-status". This message includes the requestId and the status as a string ("CANCELLED", "FAILED", "COMPLETED", "PENDING", "PROCESSING", "EXPIRED").The parent window listens for these messages to update its UI in real-time.

Example: Listening in the Parent Window

window.addEventListener("message", (event) => {
    // IMPORTANT: Verify event.origin for security!
    if (event.origin !== "https://vudy.me") return;

    const data = event.data;
    if (data && data.type === "request-status") {
        // Do whatever you want with the status and requestId
        console.log(status, requestId);
    }
});

Example: Listening in the Parent WIndow (React)

"use client";

import { useEffect, useRef } from "react";

interface IframeWrapperProps {
  src: string;
  requestId: number;
  generatedId: string;
}

export function IframeWrapper({ src, requestId, generatedId }: IframeWrapperProps) {
  const iframeRef = useRef<HTMLIFrameElement>(null);

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.data && typeof event.data === "object") {
        const { type, requestId, status } = event.data;
        
        if (type === "request-status") {
          // Do whatever you want with the status and requestId
          console.log(status, requestId);
        }
      }
    };

    // Clean up the event listener when the component unmounts
    window.addEventListener("message", handleMessage);
    return () => {
      window.removeEventListener("message", handleMessage);
    };
  }, [requestId, generatedId]);

  return (
    <div className="flex-1 w-full">
      <iframe
        ref={iframeRef}
        src={src}
        className="w-full h-full border-0 bg-transparent"
        allow="payment"
        width="100%"
        height="600px"
      />
    </div>
  );
} 

For broader real-time event handling, consider using webhooks.

Last updated