javascript:检查 iframe url 是否是同一域或外部域
我知道我无法访问显示来自另一个域的页面的 iframe 中的数据。这完全没问题,但我想检测 iframe 当前是否显示来自我的域或外部内容的页面。
我的第一次尝试是尝试访问
$('iframe')[0].contentWindow.document
包含在 try {} catch {}
中的内容,如果抛出错误,则意味着我无法访问它,因此 iframe 页面必须是外部的。 这听起来像是一个完美的解决方案,但问题是 safari 向 javascript 控制台发布了一条“不安全的 JavaScript 尝试使用 URL 访问框架”消息。 这不仅丑陋,而且可能会导致其他或未来的浏览器向用户显示明确的安全警告?
I know I can't access data in an iframe which displays a page from another domain. That's perfectly fine, but I'd like to detect, whether the iframe currently shows a page from my domain or something external.
My first attempt would be to try to access
$('iframe')[0].contentWindow.document
wrapped in try {} catch {}
, and if an error is thrown it means I can't access it, and therefore the iframe page must be external.
This sounds like a perfect solution, but the thing is safari posts a "Unsafe JavaScript attempt to access frame with URL" message to the javascript console.
This is not just ugly, but may cause other or future browsers to display explicit security warnings to the user?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试使用 postMessage 吗?
如果没有响应,则为外部域。
Can you try using postMessage?
If there is no response, it is an external domain.
如果这是您的 HTML:
不是那么简单吗:
然后用它来与您的域进行比较?
If this is your HTML:
wouldn't it be just that simple:
and then use it to compare to your domain?
为什么不检查 iframe 中的 href 属性是否与您的域相同?
Why not check if the href attribute from the iframe is the same as your domain?