How to get event when iframe src is changed in react.js?

by elisha_langworth , in category: Javascript , 3 months ago

How to get event when iframe src is changed in react.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , 2 months ago

@elisha_langworth 

To get an event when the src attribute of an <iframe> element is changed in a React component, you can create a custom wrapper component that listens for changes to the src attribute.


Here's an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React, { useEffect, useRef } from "react";

const CustomIframe = props => {
  const iframeRef = useRef(null);

  useEffect(() => {
    const observer = new MutationObserver(mutationsList => {
      for (let mutation of mutationsList) {
        if (mutation.type === "attributes" && mutation.attributeName === "src") {
          const newSrc = mutation.target.getAttribute("src");
          console.log("Src changed to:", newSrc);
          // You can trigger any custom event or callback here
        }
      }
    });

    observer.observe(iframeRef.current, { attributes: true, attributeFilter: ["src"] });

    return () => {
      observer.disconnect();
    };
  }, []);

  return <iframe ref={iframeRef} {...props} />;
};

export default CustomIframe;


In this component, we use a MutationObserver to watch for changes to the src attribute of the <iframe> element. When the src attribute changes, the console log will show the new src value. You can replace the console log with any custom event or callback you want to trigger when the src changes.


To use this custom <CustomIframe> component:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import React from "react";
import CustomIframe from "./CustomIframe";

const MyComponent = () => {
  const newSrc = "https://example.com/newurl";

  return <CustomIframe src={newSrc} />;
};

export default MyComponent;


Now, whenever the src attribute of the <CustomIframe> component changes, the event or callback you define in the component will be triggered.