skip to Main Content

I have a common react project deployed on the server. I need to call 1 of its page on my button click so I am calling the page using iFrame and am able to load the page.

<iframe
  autoFocus={true}
  title='test'
  minLength={100}
  width={"100%"}
  height={1000}
  src='http://xyz:8001/?param1=a&param2=b&param3=c'
/>

Now I need to pass some data to the iframe, hence passing it as query param "?param1=a&param2=b&param3=c", so that I frame can display it.

sample server page which I am loading in iFrame.

const ServerComponent = (props) => {
  return (
    <div id="server-component">
      <h1>param1</h1>
      <h1>param2</h1>
      <h1>param3</h1>
    </div>
  );
};

How to read and parse url data in the iFrame? Or is there another way to send data from the parent page to iFrame?

Both local and server components are in react.

2

Answers


  1. Use URLSearchParams to extract the query parameters from the url.

    For example:

    const ServerComponent = (props) => {
        const queryParams = new URLSearchParams(window.location.search);
    
        return (
          <div id="server-component">
           { 
               Object.entries(queryParams).map(([key, value]) => 
                 <h1>{key}={value}</h1>
               );
           }
          </div>
        );
      };
    
    Login or Signup to reply.
  2. You can use postMessage (as @Alanhaha added in the comment), especially if your iframe is on a different origin (protocol, domain, port combo).

    const App = () => {
      const ref = useRef();
      useEffect(() => {
         const iframe = ref.current;
         iframe.addEventListener('load', () => {
             iframe.contentWindow.postMessage('message', 'https://jcubic.pl');
         });
      }, [ref]);
        
        return (
            <iframe
                ref={ref}
                autoFocus={true}
                title='test'
                minLength={100}
                width={"100%"}
                height={1000}
                src='http://xyz:8001/?param1=a&param2=b&param3=c'
             />
        );
    }
    

    See the code in action: https://codepen.io/jcubic/pen/vYQxgrX?editors=0010

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search