我有两个子域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.
有可能修复这个问题吗?
这不是一个bug,这是一个安全特性。否则,其他人可以在你的用户不知情的情况下打开你的网站,并将数据注入你的页面。
阅读:http://en.wikipedia.org/wiki/Same_origin_policy
当然,拥有相同的SLD可能表明它们来自相同的来源,但这并不能保证是这种情况,例如,允许免费子域名的托管站点将容易受到攻击。
可以在www.example.com和api.example.com之间传递数据,但不能使用window.opener。您可以在.example.com
域(不是www.example.com)上使用Javascript (document.cookie
)在cookie中设置一个值,并且它将在www.example.com和api.example.com上可读。
在一个来自www.example.com的页面上,如果你执行这个Javascript:(来源:http://techpatterns.com/downloads/javascript_cookies.php)然后"somename" cookie将从apii.example.com
中读取。function 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");
<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>
<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>
<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>