I have an iframe for a cross-domain site. I want to read the DOM of the iframe, which I believed was possible because using the inspector, I can even modify the DOM of an iframe. Every way I attempt to read it, however, I run into the same origin policy. All I want, is the content loaded in my local DOM, from the iframe. I thought it would be as simple as
$(document.body).find('iframe').html(), but that's returning the empty string.
I really hope there's a way to do this since the work I've been doing for the last several days has been predicated on this being do-able.
There is a simple way.
You create an iframe which have for source something like "http://your-domain.com/index.php?url=http://the-site-you-want-to-get.com/unicorn
Then, you just get this url with
$_GET and display the contents with
You will obtain an iframe which has a domain same than yours, then you will be able to use the
$("iframe").contents().find("body") to manipulate the content.
If you have access to the iframed page you could use something like easyXDM to make function calls in the iframe and return the data.
If you don't have access to the iframed page you will have to use a server side solution. With PHP you could do something quick and dirty like:
<?php echo file_get_contents('http://url_of_the_iframe/content.php'); ?>
If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.
There's a workaround to achieve it.
First, bind your iframe to a target page with relative url. The browsers will treat the site in iframe the same domain with your website.
In your web server, using a rewrite module to redirect request from the relative url to absolute url. If you use IIS, I recommend you check on IIRF module.
©2020 All rights reserved.