javascript:检查 iframe url 是否是同一域或外部域

发布于 2024-12-04 19:34:13 字数 371 浏览 3 评论 0原文

我知道我无法访问显示来自另一个域的页面的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

十年九夏 2024-12-11 19:34:13

您可以尝试使用 postMessage 吗?

如果没有响应,则为外部域。

Can you try using postMessage?

If there is no response, it is an external domain.

許願樹丅啲祈禱 2024-12-11 19:34:13

如果这是您的 HTML:

<iframe src="http://www.google.com" width="100%" height="300" id='iframe'>
  <p>Your browser does not support iframes.</p>
</iframe>

不是那么简单吗:

var iframeEl = document.getElementById('iframe')
var src = iframeEl.src;

然后用它来与您的域进行比较?

If this is your HTML:

<iframe src="http://www.google.com" width="100%" height="300" id='iframe'>
  <p>Your browser does not support iframes.</p>
</iframe>

wouldn't it be just that simple:

var iframeEl = document.getElementById('iframe')
var src = iframeEl.src;

and then use it to compare to your domain?

最冷一天 2024-12-11 19:34:13

为什么不检查 iframe 中的 href 属性是否与您的域相同?

parent.frames[1].location.href;

Why not check if the href attribute from the iframe is the same as your domain?

parent.frames[1].location.href;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文