好的,我有一个页面在这个页面上有一个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时,我一直得到相同的访问拒绝错误。因此,即使子域也可以算作跨站脚本,这是正确的,还是我做错了什么?


当前回答

有一个跨浏览器的脚本获取父源:

private getParentOrigin() {
  const locationAreDisctint = (window.location !== window.parent.location);
  const parentOrigin = ((locationAreDisctint ? document.referrer : document.location) || "").toString();

  if (parentOrigin) {
    return new URL(parentOrigin).origin;
  }

  const currentLocation = document.location;

  if (currentLocation.ancestorOrigins && currentLocation.ancestorOrigins.length) {
    return currentLocation.ancestorOrigins[0];
  }

  return "";
}

这段代码,应该在Chrome和Firefox上工作。

其他回答

我不能得到以前的解决方案的工作,但我发现,如果我设置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时,子域仍然被认为是单独的域。可以使用postMessage(…)传递消息,但其他JS api被故意设置为不可访问。

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

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

var url = (window.location != window.parent.location) ? document.referrer: document.location;

我发现上面的例子建议以前工作时,脚本正在执行的iframe,但它没有 当脚本在iframe之外执行时检索url, 需要稍作调整:

var url = (window.location != window.parent.location) ? document.referrer: document.location.href;

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