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


当前回答

获取所有父Iframe函数和HTML

var parent = $(window.frameElement).parent();
        //alert(parent+"TESTING");
        var parentElement=window.frameElement.parentElement.parentElement.parentElement.parentElement;
        var Ifram=parentElement.children;      
        var GetUframClass=Ifram[9].ownerDocument.activeElement.className;
        var Decision_URLLl=parentElement.ownerDocument.activeElement.contentDocument.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上工作。

PHP $_SERVER['HTTP_REFFERER']的问题是它给出了将您带到父页面的页面的完全限定页面url。这和父页面本身不一样。更糟糕的是,有时没有http_referer,因为用户输入了父页面的url。如果我从yahoo.com到你的父页面,yahoo.com就变成http_referer,而不是你的页面。

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

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

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

我不能得到以前的解决方案的工作,但我发现,如果我设置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];