我有两个子域www.example.com
和api.example.com
。在第一个域的页面上,我打开带有URL api.example.com/some/url
的弹出窗口,并希望使用window.opener
对象将数据传递给父页面。但我得到错误:
Unsafe JavaScript attempt to access frame with URL http://www.example.com/some/page from frame with URL http://api.example.com/some/url. Domains, protocols and ports must match.
是否可以解决问题?
答案 0 :(得分:6)
这不是一个错误,它是一个安全功能。否则,其他人可以让他们的网站从他们的网站开放,并在用户不知情的情况下将数据注入您的网页。
阅读:http://en.wikipedia.org/wiki/Same_origin_policy
当然,拥有相同的SLD可能表明它们来自同一个来源,但不能保证是这种情况,例如,托管允许免费子域的网站将容易受到攻击。
答案 1 :(得分:2)
可以在www.example.com和api.example.com之间传递数据,但不能使用window.opener传递数据。您可以在document.cookie
域(不是www.example.com)上使用Javascript(.example.com
)在Cookie中设置值,并且可以在www.example.com和api.example.com上阅读
在www.example.com的页面上,如果您执行此Javascript: (来源:http://techpatterns.com/downloads/javascript_cookies.php) 然后可以从api.example.com
读取“somename”cookiefunction Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );
/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}
Set_Cookie("somename", "somevalue", 0, "/", ".example.com");
答案 2 :(得分:0)
<script>
document.domain = 'facebook.com';
try {
try{
if (window.opener && window.opener.graphexplorer) {
window.opener.graphexplorer.authCallback(window.location.hash);
}
}catch(e){}
}
catch (e) {}
window.location.hash = '';
window.close();
</script>
答案 3 :(得分:-3)
<script> document.domain = 'facebook.com'; try { try{if (window.opener && <script> document.domain = 'facebook.com'; try { try{if (window.opener && window.opener.graphexplorer) { window.opener.graphexplorer.authCallback(window.location.hash); }}catch(e){}} catch (e) {} window.location.hash = ''; window.close(); </script>) { window.opener.graphexplorer.authCallback(window.location.hash); }}catch(e){}} catch (e) {} window.location.hash = ''; window.close(); </script>
答案 4 :(得分:-5)
<script> document.domain = 'facebook.com'; try { try{if (window.opener && window.opener.graphexplorer) { window.opener.graphexplorer.authCallback(window.location.hash); }}catch(e){}} catch (e) {} window.location.hash = ''; window.close(); </script>