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¶m2=b¶m3=c'
/>
Now I need to pass some data to the iframe, hence passing it as query param "?param1=a¶m2=b¶m3=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
Use URLSearchParams to extract the query parameters from the url.
For example:
You can use postMessage (as @Alanhaha added in the comment), especially if your iframe is on a different origin (protocol, domain, port combo).
See the code in action: https://codepen.io/jcubic/pen/vYQxgrX?editors=0010