programing

iframe이 jQuery에서 로드를 완료했을 때 이벤트를 실행하려면 어떻게 해야 합니까?

instargram 2023. 8. 20. 10:14
반응형

iframe이 jQuery에서 로드를 완료했을 때 이벤트를 실행하려면 어떻게 해야 합니까?

페이지 내에 PDF를 로드해야 합니다.

이상적으로는 PDF가 로딩되면 교체되는 애니메이션 gif 로딩을 원합니다.

시도해 보셨습니까?

$("#iFrameId").on("load", function () {
    // do something once the iframe is loaded
});

저는 그것이 이루어질 수 없다고 꽤 확신합니다.

PDF 이외의 거의 모든 것이 작동하며 플래시도 작동합니다. (Safari, Firefox 3, IE 7에서 테스트됨)

안됐군요.

저에게 (pdf가 다른"pdf 은저도에되움니습었가, 다이다른또").onload 내용 "저항성" 내용):

<iframe id="frameid" src="page.aspx"></iframe>
<script language="javascript">
    iframe = document.getElementById("frameid");

    WaitForIFrame();

    function WaitForIFrame() {
        if (iframe.readyState != "complete") {
            setTimeout("WaitForIFrame();", 200);
        } else {
            done();
        }
    }

    function done() {
        //some code after iframe has been loaded
    }
</script>  

이게 도움이 되길 바랍니다.

저는 이것을 시도하고 있고 저를 위해 일하는 것 같습니다: http://jsfiddle.net/aamir/BXe8C/

PDF 파일 크기: http://jsfiddle.net/aamir/BXe8C/1/

$("#iFrameId").ready(function (){
    // do something once the iframe is loaded
});

대신에 .ready를 시도해 보셨습니까?

저는 이에 대한 즉각적인 접근 방식을 시도했지만 PDF 콘텐츠에 대해 테스트한 적은 없지만 일반 HTML 기반 콘텐츠에 대해서는 작동했습니다. 다음과 같이 설명합니다.

1단계: iframe을 div 래퍼로 감싸기

2단계: div 래퍼에 배경 이미지를 추가합니다.

.wrapperdiv{
  background-image:url(img/loading.gif);
  background-repeat:no-repeat;
  background-position:center center; /*Can place your loader where ever you like */
}

3단계: 유리 프레임 태그 추가ALLOWTRANSPARENCY="false"

iframe이 로드된 후 iframe이 로드될 때까지 로딩 애니메이션을 래퍼 div에 표시하는 것입니다.

한번 해보라구요.

jquery Load와 Ready를 모두 사용하는 것은 iframe이 진정으로 준비되었을 때 둘 다 실제로 일치하지 않는 것처럼 보였습니다.

저는 결국 이런 일을 하게 되었습니다.

$('#iframe').ready(function () {
    $("#loader").fadeOut(2500, function (sender) {
        $(sender).remove();
    });
});

여기서 #loader는 스피너 gif가 있는 iframe 위에 절대적으로 위치한 div입니다.

@알렉소는 그것을 유감스럽게 생각합니다. 당신의 약만당에 요?iframe다음과 같은 HTML 문서가 있었습니다.

<html>
  <head>
    <meta http-equiv="refresh" content="0;url=/pdfs/somepdf.pdf" />
  </head>
  <body>
  </body>
</html>

확실히 해킹이지만 파이어폭스에 효과가 있을지도 모릅니다.하지만 그 경우 로드 이벤트가 너무 빨리 시작되지 않을까 생각합니다.

iFrame에서 pdf를 로드하는 동안 로더를 보여줘야 했기 때문에 다음과 같은 결과가 나왔습니다.

    loader({href:'loader.gif', onComplete: function(){
            $('#pd').html('<iframe onLoad="loader.close();" src="pdf" width="720px" height="600px" >Please wait... your report is loading..</iframe>');
    }
    });

로더를 보여주고 있습니다.고객이 내 로더를 볼 수 있다고 확신하면 iframe을 로드하는 Completloaders 메서드를 호출합니다.iframe에 "onLoad" 이벤트가 있습니다.PDF가 로드되면 로더를 숨기는 인양 이벤트에 트리거합니다 :)

중요한 부분:

iFrame에는 필요한 작업(로더 숨기기 등)을 수행할 수 있는 "onLoad" 이벤트가 있습니다.

function frameLoaded(element) {
    alert('LOADED');
};
 <iframe src="https://google.com" title="W3Schools Free Online Web Tutorials" onload="frameLoaded(this)"></iframe> 

다음은 Firefox, IE, Opera 및 Safari에서 작동하는 작업입니다.

<script type="text/javascript">
  $(document).ready(function(){
    doMethod();
  });
  function actionIframe(iframe)
  {
    ... do what ever ...
  }
  function doMethod()
  {   
    var iFrames = document.getElementsByTagName('iframe');

    // what ever action you want.
    function iAction()
    {
      // Iterate through all iframes in the page.
      for (var i = 0, j = iFrames.length; i < j; i++)
      {
        actionIframe(iFrames[i]);
      }
    }

    // Check if browser is Safari or Opera.
    if ($.browser.safari || $.browser.opera)
    {
      // Start timer when loaded.
      $('iframe').load(function()
      {
        setTimeout(iAction, 0);
      }
      );

      // Safari and Opera need something to force a load.
      for (var i = 0, j = iFrames.length; i < j; i++)
      {
         var iSource = iFrames[i].src;
         iFrames[i].src = '';
         iFrames[i].src = iSource;
      }
    }
    else
    {
      // For other good browsers.
      $('iframe').load(function()
      {
        actionIframe(this);
      }
      );
    }
  }
</script>

다운로드가 완료되면 브라우저의 열기/저장 인터페이스가 사용자에게 팝업될 것으로 예상할 수 있는 경우 다운로드를 시작할 때 다음을 실행할 수 있습니다.

$( document ).blur( function () {
    // Your code here...
});

대화 상자가 페이지 맨 위에 나타나면 블러 이벤트가 트리거됩니다.

PDF 파일이 로드된 후 iframe 문서에 새 DOM 요소가 추가됩니다.<embed/>그래서 우리는 다음과 같이 점검할 수 있습니다.

    window.onload = function () {


    //creating an iframe element
    var ifr = document.createElement('iframe');
    document.body.appendChild(ifr);

    // making the iframe fill the viewport
    ifr.width  = '100%';
    ifr.height = window.innerHeight;

    // continuously checking to see if the pdf file has been loaded
     self.interval = setInterval(function () {
        if (ifr && ifr.contentDocument && ifr.contentDocument.readyState === 'complete' && ifr.contentDocument.embeds && ifr.contentDocument.embeds.length > 0) {
            clearInterval(self.interval);

            console.log("loaded");
            //You can do print here: ifr.contentWindow.print();
        }
    }, 100); 

    ifr.src = src;
}

제가 이 상황에 적용한 해결책은 단순히 절대 로딩 이미지를 DOM에 배치하는 것입니다. 이 이미지는 iframe이 로드된 후 iframe 레이어로 덮일 것입니다.

iframe의 z-index는 (loading's z-index + 1) 또는 그 이상이어야 합니다.

예:

.loading-image { position: absolute; z-index: 0; }
.iframe-element { position: relative; z-index: 1; }

JavaScript 솔루션이 도움이 되지 않았다면 도움이 되기를 바랍니다.저는 CSS가 이러한 상황에 가장 적합하다고 생각합니다.

안부 전합니다.

언급URL : https://stackoverflow.com/questions/30005/how-do-i-fire-an-event-when-a-iframe-has-finished-loading-in-jquery

반응형