Getting iframe current src url in cross domain

14,513

If you don't control the iFrame content, then the only solution is to create a proxy that injects the following line of code into every page.

window.postMessage(window.location,'*');

Then on the parent page you can listen for the message.

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

function receiveMessage(event) {
  console.log(event.data);
}
Share:
14,513
Fallouturama
Author by

Fallouturama

Updated on June 28, 2022

Comments

  • Fallouturama
    Fallouturama almost 2 years

    I have an iframe in my web app and I need to get its current url from the parent document (also when the user navigates the frame and change the original source url).

    Url is needed simply to social share it.

    As a cross-domain scenario, I don't own the child document (its a remote domain).

    I am aware of the same-origin-policy that prevents cross domain access from parent document to child one, but I'm looking for a solution by any creative mean possible - there has to be a way around.

  • feedc0de
    feedc0de over 6 years
    If I use a proxy then the domain could be the same as my website itself. Then I could access the iframe, right?
  • David Bradshaw
    David Bradshaw over 6 years
    That is correct