detect iframe load error

前端 未结 3 779
清酒与你
清酒与你 2021-02-07 10:13

I am loading a user-selected page into an iframe using the src property. If the load fails, I would like to report the problem in terms that will make sense to the user. iframe

3条回答
  •  我在风中等你
    2021-02-07 10:16

    Late to the party, but I've managed to crack it:

    At first, I thought to do an AJAX call like everyone else, except that it didn't work for me initially, as I had used jQuery. It works perfectly if you do a XMLHttpRequest:

    var url = http://url_to_test.com/
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status != 200) {
            console.log("iframe failed to load");
        }
    };
    xhttp.open("GET", url, true);
    xhttp.send();
    

    Edit:
    So this method works ok, except that it has a lot of false negatives (picks up a lot of stuff that would display in an iframe) due to cross-origin malarky. The way that I got around this was to do a CURL/Web request on a server, and then check the response headers for a) if the website exists, and b) if the headers had set x-frame-options.

    This isn't a problem if you run your own webserver, as you can make your own api call for it.

    My implementation in node.js:

    app.get('/iframetest',function(req,res){ //Call using /iframetest?url=url - needs to be stripped of http:// or https://
       var url = req.query.url; 
        var request = require('https').request({host: url}, function(response){ //This does an https request - require('http') if you want to do a http request
            var headers = response.headers;
            if (typeof headers["x-frame-options"] != 'undefined') {
                res.send(false); //Headers don't allow iframe
            } else {
                res.send(true); //Headers don't disallow iframe
            }
        });
        request.on('error',function(e){
           res.send(false); //website unavailable
        });
        request.end();
    });
    

提交回复
热议问题