AverageAsker
AverageAsker

Reputation: 188

How to access query string parameters inside IFRAME after a redirect back

I have an HTML Host1Page with an IFRAME, the IFRAME's attribute sandbox doesn't include allow-top-navigation so the hosting page is not affected by any navigation which could be requested inside the IFRAME. Originally the IFRAME renders static HTML I supply but then, once a user interacts with it in a certain way, the HTML's javascript redirects the current window, which is the IFRAME's content in my case, to another host - Host2Page. As a result the IFRAME renders a content of the Host2Page. Want to emphasis I'm not setting the IFRAME's src property but instead setting the window.location.href, I cannot change the way the redirect is done because I don't own the code making that redirect. Once a user finishes interacting with that another site, Host2Page, the user is redirected back to the Uri corresponding to the page hosting my IFRAME - Host1Page, while redirecting the Host2Page is supplying some data via query parameters. How do I get access to that query parameter from within the IFRAME?

I tried employing myIFrame.contentWindow.location.search - but it always is empty and the myIFrame.contentWindow.location.href is always, before and after the redirect to that another site, pointing to the Uri of the page Host1Page hosting the IFRAME.

Upvotes: 2

Views: 3121

Answers (1)

Ed Lucas
Ed Lucas

Reputation: 7305

If you control the content of the IFRAME that's being loaded after the second redirect, you could use postMessage to send the parameter values to the parent page.

const querystringParams = new URLSearchParams(window.location.search);
const querystringValue = querystringParams.get('paramINeed');

window.parent.postMessage(querystringValue, targetOrigin);

To receive the message on your parent page:

window.addEventListener("message", receiveMessage, false);

with receiveMessage being a function which takes an event object as a parameter.

See: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Upvotes: 1

Related Questions