Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get url from iframe when origin is not the same

I want to get the URL from an iframe when the user redirects by clicking links in the iframe. The source of the iframe is not the same as the web application.

For example:

<iframe src="startingUrl" class="embed-responsive-item" id="iframe" sandbox="" allowfullscreen</iframe>

I add a load listener on the iframe to detect when the user redirects to other urls in this iframe:

const iframe = document.getElementById("iframe");

iframe.addEventListener("load", (evt) => {
    const location = iframe.contentWindow.location;

    console.log(location); // this gives me a Location object where I can see the href property
    console.log(location.href); // this gives me a SecurityError: Permission denied to get property "href" on cross-origin object, I also tried to get a copy of the object but that doesn't work either.
});

I know what causes this problem and I also know it is not possible. But I need to find a way to get the current URL of the page. If this is a no go then I want that the user who uses this web application can copy the url of the iframe and put it in an input field.

Now they can do "View frame source" in chrome and This frame: view frame source or info in Firefox. But this is too complicated for the user. Is there a way they can see the URL in the iFrame or a way for the user to get the URL simpler.

The site in the iFrame is not mine.

All help is much appreciated!

like image 249
Laurent Dhont Avatar asked Nov 26 '19 00:11

Laurent Dhont


1 Answers

Short answer: This is a no go, unless you have the support of the other site in your iframe and they are willing to add the code in @박상수 answer.

Longer answer: You could set up a proxy server to inject the required code to make this work, but then you will run into legal and ethical difficulties, so I am not going to explain how to do that in depth.

Another approach might be to create a browser extension and have your users install that. Again I should point out FaceBook has in the past ran into ethical difficulties taking this approach.

Ultimately their are very good security reasons why the browser stops you doing this and you should probably respect those reasons and not do it.

like image 183
David Bradshaw Avatar answered Oct 04 '22 22:10

David Bradshaw