How to get the current url accessing by this iframe?
redwolfgang24 opened this issue ยท 4 comments
I just wonder if we can get the current URL of the iframe.
@redwolfgang24 do you mind explaining your use case?
The URL of the iframe will usually be the attributes.src
you pass in to IframeComm.
@pbojinov what I need is to get the URL of the current iframe. ex. I embedded the payment gateway to the iframe. If payment success the URL of the iframe will change to the same domain of the parent. I have to listen to every activity inside the iframe and the same time check if the URL changes so that I can trigger a redirection if that happens.
Thank you for providing the use case. I'm actually doing something very similar as well.
There's three ways to approach this, one that is currently supported (which I recommend) and two ways that have not yet been implemented (feel free to submit a pull request).
Current solution:
- Have your iframe send a message to the parent notifying it that it has changed URLs.
// iframe
window.parent.postMessage('url_changed', '*');
// inside your react parent component - received a message from iframe
const onReceiveMessage = event => {
console.info('onReceiveMessage', event);
let { origin, data } = event;
switch (data) {
case 'url_changed':
// do something
break;
default:
break;
}
};
I left the targetOrigin as *
for demo purposes but note that you should always provide a specific targetOrigin, not *
, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.
Alternative Solutions:
-
Expose the iframe
ref
through a callback function when the iframe loads. Then on an interval you can inspect the iframe src usingthis._frame.src
. -
If the iframe domain matches the parent domain, then you can read the location using
this._frame.contentWindow.location.href
in the iframe's onload function. This can then be passed to the parent through a function likeonIframeNavigation
, similar to howonReceiveMessage
pass data back up.
@pbojinov Thank you so much for this one. I will try this one later. ๐