Nice programing

iframe src가로드에 실패하면 오류를 포착합니다.

nicepro 2020. 11. 15. 11:44
반응형

iframe src가로드에 실패하면 오류를 포착합니다. 오류 :-“프레임에 'http://www.google.co.in/'표시를 거부했습니다 ..”


Knockout.jsiframe src태그 를 바인딩 하는 사용 하고 있습니다 (사용자와 관련하여 구성 할 수 있음).

이제 사용자가 http://www.google.com 을 구성한 경우 (iframe에서로드되지 않는다는 것을 알고 있으므로 -ve 시나리오에 사용하고 있습니다) IFrame에 표시되어야합니다. 하지만 오류가 발생합니다.

'X-Frame-Options'를 'SAMEORIGIN'으로 설정했기 때문에 프레임에 ' http://www.google.co.in/ ' 을 표시하는 것을 거부했습니다 .

Iframe에 대한 다음 코드가 있습니다.

<iframe class="iframe" id="iframe" data-bind="attr: {src: externalAppUrl, height: iframeheight}">
    <p>Hi, This website does not supports IFrame</p>
</iframe>

내가 원하는 것은 URL이로드되지 않는 경우입니다. 사용자 지정 메시지 를 표시하고 싶습니다 . 오류 발생시 콘솔 스크린 샷 여기에 FIDDLE

이제 onload 및 onerror를 다음과 같이 사용하면

<iframe id="browse" style="width:100%;height:100%" onload="alert('Done')" onerror="alert('Failed')"></iframe>

w3schools.com로드는 잘 작동하지만 google.com에서는 작동하지 않습니다.

둘째 :-내가 그것을 함수로 만들고 바이올린에서했던 것처럼 시도하면 작동하지 않습니다.

<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>

어떻게 실행하고 오류를 캡처해야하는지 모르겠습니다.

편집 됨 : -iframe이 stackoverflow 에서 질문을 로드하거나로드하지 않는 경우 함수를 호출하고 싶지만 iframe에로드 할 수있는 사이트에 대한 오류 가 표시되는 것을 보았습니다 .

또한 로드 이벤트시 Stackoverflow iframe을 살펴 보았습니다. 감사합니다 !!


브라우저에서 설정 한 동일한 원본 정책으로 인해 클라이언트 측에서이 작업을 수행 할 수 없습니다 . 너비 및 높이와 같은 기본 속성 외에는 iFrame에서 많은 정보를 얻을 수 없습니다.

또한 Google은 응답 헤더 에 SAMEORIGIN 의 ' X-Frame-Options '를 설정합니다.

Google에 ajax 호출을하더라도 브라우저가 동일한 출처 정책을 시행하기 때문에 응답을 검사 할 수 없습니다.

따라서 유일한 옵션은 IFrame에 사이트를 표시 할 수 있는지 확인하기 위해 서버에서 요청하는 것입니다.

따라서 서버에서 웹 앱은 www.google.com에 요청한 다음 응답을 검사하여 X-Frame-Options의 헤더 인수가 있는지 확인합니다. 존재하는 경우 IFrame에서 오류가 발생한다는 것을 알 수 있습니다.


loadiframe 이벤트를 바인딩 할 수 있다고 생각합니다 . iframe 콘텐츠가 완전히로드되면 이벤트가 발생합니다.

동시에 setTimeout을 시작할 수 있습니다. iFrame이로드되면 시간 제한을 지우거나 시간 제한이 실행되도록합니다.

암호:

var iframeError;

function change() {
    var url = $("#addr").val();
    $("#browse").attr("src", url);
    iframeError = setTimeout(error, 5000);
}

function load(e) {
    alert(e);
}

function error() {
    alert('error');
}

$(document).ready(function () {
    $('#browse').on('load', (function () {
        load('ok');
        clearTimeout(iframeError);
    }));

});

데모 : http://jsfiddle.net/IrvinDominin/QXc6P/

두 번째 문제

인라인 함수 호출에서 괄호를 놓치기 때문입니다. 이것을 변경하십시오 :

<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>

이것으로 :

<iframe id="browse" style="width:100%;height:100%" onload="load('Done func');" onerror="error('failed function');"></iframe>

데모 : http://jsfiddle.net/IrvinDominin/ALBXR/4/


onload는 항상 트리거되며,이 문제는 try catch 블록을 사용합니다. contentDocument를 가져 오려고 할 때 예외가 발생합니다.

iframe.onload = function(){
   var that = $(this)[0];
   try{
        that.contentDocument;
   }
   catch(err){
        //TODO 
   }
}

이것은 Edens 답변에 대한 약간의 수정입니다-크롬에서 나를 위해 오류를 포착하지 못했습니다. 콘솔에 여전히 오류가 표시되지만 " 'X-Frame-Options'를 'sameorigin'으로 설정했기 때문에 프레임에 ' https://www.google.ca/ ' 를 표시하는 것을 거부했습니다 ." 적어도 이것은 오류 메시지를 포착하고 처리 할 수 ​​있습니다.

 <iframe id="myframe" src="https://google.ca"></iframe>

 <script>
 myframe.onload = function(){
 var that = document.getElementById('myframe');

 try{
    (that.contentWindow||that.contentDocument).location.href;
 }
 catch(err){
    //err:SecurityError: Blocked a frame with origin "http://*********" from accessing a cross-origin frame.
    console.log('err:'+err);
}
}
</script>

I faced similar problem. I solved it without using onload handler.I was working on AngularJs project so i used $interval and $ timeout. U can also use setTimeout and setInterval.Here's the code:

 var stopPolling;
 var doIframePolling;
 $scope.showIframe = true;
 doIframePolling = $interval(function () {
    if(document.getElementById('UrlIframe') && document.getElementById('UrlIframe').contentDocument.head && document.getElementById('UrlIframe').contentDocument.head.innerHTML != ''){
        $interval.cancel(doIframePolling);
        doIframePolling = undefined;
        $timeout.cancel(stopPolling);
        stopPolling = undefined;
        $scope.showIframe = true;
    }
},400);

stopPolling = $timeout(function () {
        $interval.cancel(doIframePolling);
        doIframePolling = undefined;
        $timeout.cancel(stopPolling);
        stopPolling = undefined;
        $scope.showIframe = false;     
},5000);

 $scope.$on("$destroy",function() {
        $timeout.cancel(stopPolling);
        $interval.cancel(doIframePolling);
 });

Every 0.4 Seconds keep checking the head of iFrame Document. I somthing is present.Loading was not stopped by CORS as CORS error shows blank page. If nothing is present after 5 seconds there was some error (Cors policy) etc.. Show suitable message.Thanks. I hope it solves your problem.


I have the same problem, chrome can't fire onerror when iframe src load error.

but in my case, I just need make a cross domain http request, so I use script src/onload/onerror instead of iframe. it's working well.


I solved it with window.length. But with this solution you can take current error (X-Frame or 404).

iframe.onload = event => {
   const isLoaded = event.target.contentWindow.window.length // 0 or 1
}

MSDN

참고 URL : https://stackoverflow.com/questions/15273042/catch-error-if-iframe-src-fails-to-load-error-refused-to-display-http-ww

반응형