javascript 如何将 iframe 从外部站点的显示限制为仅特定域
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5224286/
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
How to limit display of iframe from an external site to specific domains only
提问by Marci
I operate a service where a client's content is prepared and displayed in an iframe. The client then copies a rudimentary iframe html tag and pastes it into their web page. Some clients complain that other websites are copying the iframe tag and pasting it into their sites.
我经营一项服务,在该服务中准备好客户的内容并将其显示在 iframe 中。然后客户端复制一个基本的 iframe html 标记并将其粘贴到他们的网页中。一些客户抱怨其他网站正在复制 iframe 标记并将其粘贴到他们的网站中。
Is it possible to restrict the display of an iframe's content to a specific domain or domains? Perhaps by programmatically telling the iframe that its parent must be some-domain.com or else don't display.
是否可以将 iframe 内容的显示限制在一个或多个特定域?也许通过以编程方式告诉 iframe 它的父级必须是 some-domain.com 否则不显示。
Does this make sense? I can sometimes be too verbose.
这有意义吗?我有时可能太冗长了。
采纳答案by HymanJoe
you can use an .htaccess (assuming the original content is on an Apache server) to limit the access to a specific IP.
您可以使用 .htaccess(假设原始内容在 Apache 服务器上)来限制对特定 IP 的访问。
Or, if the page is a PHP, you could limit it to a specific domain, like this:
或者,如果页面是 PHP,您可以将其限制为特定域,如下所示:
<?php
$continue = 0;
if(isset($_SERVER['HTTP_REFERER'])) {
//correct domain:
$ar=parse_url($_SERVER['HTTP_REFERER']);
if( strpos($ar['host'], 'yourdomain.com') === false ){
} else {
$continue = 1;
}
}
if($continue == 0){
header('HTTP/1.0 403 Forbidden');
exit('Forbidden');
}
?>
回答by Oded
Sounds like a check that is better made server side - you can check the iFrame markup against a list of valid domain names (or parent domain names) and reject it if they are invalid.
听起来像服务器端的检查更好 - 您可以根据有效域名(或父域名)列表检查 iFrame 标记,如果它们无效则拒绝它。
You could do all of the above in javascript, before injecting the iFrame into the page, but if javascript is off, your validation will not work, not to mention that with development tools on the client any javascript can be modified.
在将 iFrame 注入页面之前,您可以在 javascript 中完成上述所有操作,但是如果 javascript 关闭,您的验证将不起作用,更不用说使用客户端上的开发工具可以修改任何 javascript。

