自己折腾了一段时间的js,总是卡在跨域问题。
比如,自己用Java写了个后端。某一天,需要测试angular js的post请求是否正确,便想到了这个服务端,当请求的时候提示“跨域”。
今天,需要得到iframe页面对应的url,也是因为跨域,导致失败。
刚刚看到了一篇文章,说跨域问题是为了用户安全,讲的很有道理,看来以为遇到这类问题,只能想别的办法了。
原文链接:http://stackoverflow.com/questions/26055152/how-to-get-current-page-loaded-url-from-iframe
For a matter of security you are allowed to retrieve the URL as long as the contents of the iframe, and the referencing javascript, are hosted in the same domain.
Should it be the case, you can do something like:
document.getElementById("frameid").contentWindow.location.href
If the two domains are different then you'll have all the restrictions that apply to the cross-site reference scripting domain. Example:
document.getElementById("frameid").src ='/';
alert(document.getElementById("frameid").documentWindow.location.href);
Error: Permission denied to get property Location.href
For sure (except if you find some huge security flaw in your browser) you simply cannot achievewhat you need using javascript
in the parent document. Let's see with a simple example why. If the browser allowed what you need, you could easily:
- Create a page, with a hidden iframe (e.g.
http://malicous.com/dont-trust
) - In that iframe, open a child page with the login process of some website (e.g.
http://insecure-web-site.com/redirectlogin
) - If cookies for child are present and under certain circumstances, the page inside the frame will redirect to the real website, proceeding with user login.
- From the parent page now you will be able to read all the sensitive informations gone through the login process contained inside the URL, e.g. access tokens, session IDs, ...
- At this point the victim website and its users are in front of a wide new set of possible security threats...