Javascript 找出父窗口的访问因同源策略而受到限制的最佳方法是什么?
我当前的解决方案:Javascript 找出父窗口的访问因同源策略而受到限制的最佳方法是什么?,javascript,iframe,cross-domain,xss,same-origin-policy,Javascript,Iframe,Cross Domain,Xss,Same Origin Policy,我当前的解决方案: function isAccessToWindowRestricted(w) { try { return !w.location.href; } catch (e) { return true; } } 还有更好的主意吗?没有try-catch有“合法”的方法吗?没有好的方法,因为如果不抛出异常,就无法测试父帧中的值是否存在 我只是尝试了一些东西,包括: var parentURL = window.parent && wind
function isAccessToWindowRestricted(w) {
try {
return !w.location.href;
} catch (e) {
return true;
}
}
还有更好的主意吗?没有try-catch有“合法”的方法吗?没有好的方法,因为如果不抛出异常,就无法测试父帧中的值是否存在 我只是尝试了一些东西,包括:
var parentURL = window.parent && window.parent.location && window.parent.location.href;
不管怎样,由于同源策略,它都会抛出一个异常。但是,您可以简单地检查一下是否在iframe中
function checkInFrame( arg ){ arg = arg || window; return arg.parent == window; }
但据我所知,您必须使用
try{…}catch(…){…}
块(这就是它的用途)。不同的浏览器的行为不同。例如,Chrome不会抛出异常,只是返回受限windowgood to know的location.href的undefined。不幸的是,除非您只为Chrome用户编写,否则您仍然必须使用try/catch块:(