在 Facebook 应用程序中,我需要检查顶部框架(主窗口)URL 是什么,并相应地显示内容。
我尝试使用以下方法:
if (top.location.toString().toLowerCase().indexOf("facebook.com") <0) { ... }
如果页面不在 iframe 中,则效果很好,但是当页面在 iframe 中加载时(就像用作 facebook 应用程序时一样),代码会生成
"Uncaught TypeError: Property 'toString' of object # is not a function".
有什么方法可以修复此代码(具有跨浏览器兼容性 - 可能使用 jQuery)?
谢谢!
乔尔
最佳答案
跨源问题确实会阻止您访问此顶部窗口位置。但是,如果您只想要 iframe 的父窗口位置,您可以通过 document.referrer
字符串获取它。
在您的 iframe 中,您将获取 url:
var parentURL = document.referrer
https://developer.mozilla.org/en-US/docs/Web/API/document.referrer
我已经在我自己的 iframe 应用程序中成功地使用了它。另外请注意,如果您在 iframe 中导航,引荐来源网址将会改变。
Nicholas Zakas 在他的博客上发表了一篇文章: http://www.nczonline.net/blog/2013/04/16/getting-the-url-of-an-iframes-parent/
关于javascript - 获取顶部框架的URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4903351/