问题
I'd like to load external websites within an iframe, and if any of those sites employ the use of a frame blocker then I'd like to redirect the user to an error page. There have been a few proposed methods of doing this:
- wait for an onload timeout
- see if iframe src html contents are 'empty' after it loads
- Try to catch an error
- Maintain a database of 'blacklisted' urls
So far, depressingly, I've had the most luck with the last item. The other methods aren't working for the following reasons:
- waiting for an onload timeout:
- onload events fire even with websites that employ frame killers. For example, if I try to access www.google.com, it'll just load empty html structure.
- seeing if iframe src html contents are 'empty' after it loads
- You're unable to access external src contents of an iframe due to the same origin policy.
- Trying to catch an error:
- To my understanding I can only find error handling functions that pertain to errors stemming from your local JS code, and nothing related to errors like
"Refused to display <URL> in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'/'DENY'".
- To my understanding I can only find error handling functions that pertain to errors stemming from your local JS code, and nothing related to errors like
- Maintaining a database of 'blacklisted' urls:
- This is obviously a bad solution, it's incomprehensive and a big list haha.
Maybe I'm misunderstanding one of these methods. Is there a solution here I'm missing? For context I am doing this mainly in JS + jQuery.
回答1:
I have a temporary fix that uses header information as @charlietfl suggested, though it's not perfect, as you can see under the tests section, not all sites list x-frame options in their headers.
<?php
// checkXFO
// checks x-frame options
// $headers: an array of headers
// returns: nothing
function checkXFO($headers){
if($headers['X-Frame-Options']==""){
echo "good to embed! <p>";
}
else{
echo "Denied! <p>";
}
}
//-----------------------
// tests
//-----------------------
// x-frame option: SAMEORIGIN
// should deny
// > passes
$headerArray = get_headers('http://www.google.com',1);
checkXFO($headerArray);
// x-frame option: DENY
// should deny
// > passes
$headerArray = get_headers('http://www.facebook.com',1);
checkXFO($headerArray);
//x-frame option: none
// should accept
// > passes
$headerArray = get_headers('http://wikipedia.org',1);
checkXFO($headerArray);
//x-frame option: none
// should accept
// > passes
$headerArray = get_headers('http://neopets.com',1);
checkXFO($headerArray);
//x-frame options: DENY
// should deny
// > fails
$headerArray = get_headers('http://www.yahoo.com',1);
checkXFO($headerArray);
//x-frame option:none. Redirected x-frame options: DENY
// should deny
// > fails
$headerArray = get_headers('http://www.yahoo.ca',1);
checkXFO($headerArray);
?>
来源:https://stackoverflow.com/questions/41538675/detecting-if-iframe-src-is-displayable