好的,我有一个页面在这个页面上有一个iframe。我需要做的是在iframe页面上,找出主页面的URL是什么。

我四处搜索,我知道这是不可能的,如果我的iframe页面是在不同的域,因为这是跨站脚本。但我读过的所有地方都说,如果iframe页面与父页面在同一个域上,它应该工作,例如:

parent.document.location
parent.window.document.location
parent.window.location
parent.document.location.href

…或者其他类似的组合,因为似乎有多种方法可以获得相同的信息。

不管怎样,问题来了。我的iframe与主页在同一个域上,但不是在同一个SUB域上。举个例子

http:// www.mysite.com/pageA.html

然后我的iframe URL是

http:// qa-www.mysite.com/pageB.html

当我试图从pageB.html (iframe页面)抓取URL时,我一直得到相同的访问拒绝错误。因此,即使子域也可以算作跨站脚本,这是正确的,还是我做错了什么?


当前回答

下面这行就可以了:document.location。ancestry origins[0]这个返回祖先域名。

其他回答

我发现在$_SERVER['HTTP_REFERER']不工作的情况下(我在看你,Safari), $_SERVER['REDIRECT_SCRIPT_URI']一直是一个有用的备份。

我不能得到以前的解决方案的工作,但我发现,如果我设置iframe scr与例如http:otherdomain.com/page.htm?from=thisdomain.com/thisfolder然后我可以,在iframe提取thisdomain.com/thisfolder使用以下javascript:

var myString = document.location.toString();
var mySplitResult = myString.split("=");
fromString = mySplitResult[1];

假设你要告诉父页面如何设置iframe,以轻松但不安全的方式获得包含路径和URL参数的完整URL,在指定iframe时包含referrerpolicy=" not - safe- URL ":

<iframe src="https://example.com/innersite" referrerpolicy="unsafe-url" title="My Title"></iframe>

然后你可以得到完整的原始URL:

document.referrer

许多其他答案只有当iframe src与父域相同时才有效。

Fallbacks:

如果存在安全问题,您可以像https://stackoverflow.com/a/5697801/1226799所说的那样进行回退,其中父节点在iframe URL的URL参数中显式地发送其URL,但攻击者可以很容易地伪造这一点。

我相信您还可以使用消息传递并检查事件的起源:https://stackoverflow.com/a/61548595/1226799

这个问题有很多答案,但在支持或可靠性方面,没有一个肯定是最好的。

选项

window.location.ancestorOrigins[0] will get the parent url, but this api only works in chromium browsers (see support). this also supports nested iframes, where the bottom most child has access to the urls of each parent iframe. document.referrer is the most common answer but is not always reliable navigation inside of the iframe would show the last page instead of the parent frame url redirects only show the most recent referrer to the current page if the page reloads itself the referer becomes the page itself http child with an https parent has an empty string for referrer

不管用的东西

window.parent.location.href。如果父节点和子节点在不同的域中,这个api会被现代浏览器阻塞(见这里),并抛出一个错误。

建议

如果支持,我更喜欢window.location.祖宗起源[0]。文档。推荐器可以工作,但不太可靠,使其成为我的备用选项。如果您确实使用文档引用器,请尝试在第一次加载框架页面时调用它,然后再进行导航或重定向,以获取父地址。

你是正确的。当使用iframe时,子域仍然被认为是单独的域。可以使用postMessage(…)传递消息,但其他JS api被故意设置为不可访问。

还可以根据上下文获取URL。详见其他答案。