2011-02-04 106 views
4

在facebook应用程序中,我需要检查顶部框架(主窗口)的URL,并相应地显示内容。获取顶部框架的URL

我尝试使用以下内容:

if (top.location.toString().toLowerCase().indexOf("facebook.com") <0) { ... } 

如果页面不是一个iframe中,但效果很好,当页面在iframe中加载(如它的Facebook应用程序使用时)的代码生成

"Uncaught TypeError: Property 'toString' of object # is not a function".

有没有什么办法可以修复此代码(跨浏览器兼容性 - 也许与jQuery)?

谢谢!

乔尔

+1

您不能得到顶部位置,但您可以在父级使用document.referrer字符串。见下面的答案。 – mcanfield 2013-10-17 22:35:54

回答

6

你有,你不准在不同的文档域的访问top.location问题。

这是内置于浏览器的安全功能。

Read up on XSS,为什么安全防范措施到位:)

您也可以通过阅读了解到大量关于the same origin policy

+0

有趣...那么是否有任何解决方法来知道我目前是否正在通过iframe查看页面? (看到您对XSS的编辑 - 感谢这一点,我明白,访问顶部框架cookie可能会造成问题。但是获取主机名应该是允许的:/) – Joel 2011-02-04 21:58:25

+2

如果你不在iframe中`window.top === window`将返回true – 2011-02-04 22:00:16

0

你试试这个:

var location = top.location.toString().toLowerCase(); 
if (location.indexOf("facebook.com") <0) { ... } 
1

这可能工作:

if (self!=top && document.referrer.toLowerCase().indexOf("facebook.com") <0) { ... } 

...只要你不呐在框架内游荡。

但它不是个很好的办法^^

8

这是事实,跨起源问题将阻止您访问此之上的窗口位置。但是,如果您只想要iframe的父窗口位置,则可以通过document.referrer字符串获取。

在您的iframe你抓取网址:

var parentURL = document.referrer

https://developer.mozilla.org/en-US/docs/Web/API/document.referrer

我在我自己的iframe的应用程序成功使用此。另外,请注意,如果您在您的iframe中导航,引用者将会改变。

尼古拉斯Zakas在他的博客上写了: http://www.nczonline.net/blog/2013/04/16/getting-the-url-of-an-iframes-parent/

3

与马丁耶斯佩森劝修复,我可以在iFrame中检查地址和非标准顶部地址:

//this is fix for IE 
if (!window.location.origin) { 
    window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: ''); 
    } 

//and here we will get object of address 
var urls = (window.location != window.parent.location) ? document.referrer: document.location; 

//Martins adviced fix for checking if You are not in iFrame  
if (window.top === window) { 
    urls = urls.origin; 
} 

//and now indexOf works in both ways - for iFrame and standart top address 
if (urls.indexOf("facebook.com") != -1) { 
    //do stuff 
}