【问题标题】:How to check whether a web page can be loaded in iframe如何检查网页是否可以在 iframe 中加载
【发布时间】:2021-06-27 04:11:35
【问题描述】:
我正在尝试完成一项简单的任务。我希望能够检测一个网站是否可以加载到 iframe 中。如果无法加载,我想加载一个替代页面。
例如:
$website = google.com
$alternative = facebook.com
<iframe id="myframe" scrolling="no" src="<?php echo $website; ?>"></iframe>
我希望能够在加载之前检测网站 (google.com) 是否可以加载到 iframe 中。万一网站无法加载,我想加载替代方案(facebook.com)。
【问题讨论】:
标签:
javascript
php
iframe
【解决方案1】:
以下是用于执行此类检查的示例 PHP 代码 sn-p。
function isIframeDisabled($src){
try{
$headers = get_headers($src, 1);
$headers = array_change_key_case($headers, CASE_LOWER);
// Check Content-Security-Policy
if(isset($headers[strtolower('Content-Security-Policy')])){
return true;
}
// Check X-Frame-Options
if(isset($headers[strtolower('X-Frame-Options')] &&
(strtoupper($headers['X-Frame-Options']) == 'DENY' ||
strtoupper($headers['X-Frame-Options']) == 'SAMEORIGIN')
){
return true;
}
} catch (Exception $ex) {
// Ignore error
}
return false;
}