问题
I have the following page
<!DOCTYPE html>
<html>
<script type="text/javascript">
function loopLink(i)
{
window.open($('#iframe_a').contents().find('.image-navigator-mid a').attr('href'),'iframe_a');
setTimeout(function()
{
if (i < 3) loopLink(i+1);
}, 5000);
}
// Wait for the page to load first
window.onload = function() {
var a = document.getElementById("mylink");
a.onclick = function() {
loopLink(0);
return false;
}
}
</script>
<iframe src="http://nanofate.us/content/fate-new-hair-style#node-inner" width="500" height="500" name="iframe_a" id="iframe_a"></iframe>
<br />
<a id="mylink" href="">Execute</a>
the idea is that in it's current form, when you click Execute, the javascript will cause the iframe to use the "previous" link 4 times, waiting 5 second each time, however when i click the link it just reloads the page and even after waiting 10 seconds the iframe is doing nothing
i am wondering what i have done wrong
回答1:
Due to Same Origin Policy restrictions, you can not access contents of iframe if it is running a page from another domain. There are solutions to same domain policy like
- Opening a page via a proxy
Check out Tomodo. It is just to give you a hint how they used proxy to bypass same origin policy constraint and access iframe content. So the implementation idea goes like this
- Create a proxy and host it at
a.com/proxy
- Host your main page at
a.com/index.html
- Now, request your proxy to give you content of iframe_url something like this
a.com/proxy?url=iframe_url.com
Please note this is not a trivial task and you may have to handle a lot of cases at your proxy like handling relative URLs, cookie reading by iframe_url etc etc. So go for it only if you need it desperately.
Another solution might be this:
If you want to download some images for a particular domain, just ask your server side code to it for you. Your backend code will fetch the html of page and use some HTML parser like
- BeautifulSoup for python (Documentation Link)
- Jsoup for Java (Documentation Link)
to parse img tags and extract the source and fetch the images and download them.
PS: Just for some good information, please read Ways to circumvent same origin policy
回答2:
I think what you are doing is subject to the same origin policy. This should be the reason why you are getting permission denied type errors.
来源:https://stackoverflow.com/questions/20943686/unable-to-access-iframe-content-same-origin-policy