Javascript 在 iframe 中获取父页面的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5081807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:34:10  来源:igfitidea点击:

get URL of parent page inside when inside an iframe

phpjavascriptiframe

提问by Scorpion King

I have an iframe (iframe.php) inside my main page (index.php). I want to echo the URL of the main page inside the iframe. I know how to echo the URL of any page but not when it is inside an iframe. When i try this, it is echoing only the URL of the iframe and not of the main page. It sounds simple but not able to figure it out.

我的主页 (index.php) 中有一个 iframe (iframe.php)。我想在 iframe 内回显主页的 URL。我知道如何回显任何页面的 URL,但在 iframe 内时不知道。当我尝试这个时,它只回显 iframe 的 URL 而不是主页的 URL。听起来很简单,但无法弄清楚。

REASON: the reason why i chose php and why i am trying to do this is, i need to verify the URL from which this page is being accessed... do not want the iframe to be accessed unless the user is in index.php and reject the user from accessing it if he is not in the iframe of the main page.

原因:我选择 php 的原因以及我尝试这样做的原因是,我需要验证正在访问此页面的 URL... 除非用户在 index.php 中,否则不希望访问 iframe并拒绝用户访问它,如果他不在主页的 iframe 中。

回答by Emanuele

You can use

您可以使用

$_SERVER["HTTP_REFERER"]

to read the parent.

读父。

It work for me.

它对我有用。

The javascript code can't talk easily with PHP The ?from=

javascript 代码不能与 PHP 轻松对话 ?from=

回答by Chris Sobolewski

PHP has no idea about an iframe, it's just served as another page and interpreted by the browser...

PHP 不知道 iframe,它只是作为另一个页面并由浏览器解释......

You could do something like...

你可以做一些像...

<iframe src="frame.php?from=<?php echo currentPageURL() ?>">

Then inside the iframe, you can access $_GET['from']. Just make sure you verify, as that would be insecure.

然后在 iframe 内部,您可以访问$_GET['from']. 只需确保您进行验证,因为那会不安全。

Here is the code I typically use to return the current page URL:

这是我通常用于返回当前页面 URL 的代码:

function currentPageURL() {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}

回答by Maertien

Try this in iframe:

在 iframe 中试试这个:

<script type="text/javascript">alert(top.location.href);</script>

I think it should work. :-)

我认为它应该工作。:-)