복붙노트

[JQUERY] jQuery를 .ready에 동적으로 삽입은 iframe

JQUERY

jQuery를 .ready에 동적으로 삽입은 iframe

해결법


  1. 1.나는 비슷한 질문 대답 (IFRAME이 완료 로딩 때 자바 스크립트 콜백을 참조?). 다음 코드를 사용하여 iframe이로드 이벤트에 대한 제어를 얻을 수 있습니다 :

    나는 비슷한 질문 대답 (IFRAME이 완료 로딩 때 자바 스크립트 콜백을 참조?). 다음 코드를 사용하여 iframe이로드 이벤트에 대한 제어를 얻을 수 있습니다 :

    function callIframe(url, callback) {
        $(document.body).append('<IFRAME id="myId" ...>');
        $('iframe#myId').attr('src', url);
    
        $('iframe#myId').load(function() {
            callback(this);
        });
    }
    

    iframe을 다루는 나는 사용로드 이벤트 대신 문서 준비 이벤트에 좋은의 충분한을 발견했다.


  2. 2.jQuery를 다음 나를 위해 일한 1.3.2을 사용 :

    jQuery를 다음 나를 위해 일한 1.3.2을 사용 :

    $('iframe').ready(function() {
      $('body', $('iframe').contents()).html('Hello World!');
    });
    

    개정:! 사실 위의 코드는 때때로 파이어 폭스에서 작동처럼 보인다는 오페라 작품처럼 보인다 않았다.

    대신에 나는 내 목적으로 폴링 솔루션을 구현했습니다. 그것은 다음과 같습니다 아래 간체 :

    $(function() {
      function manipIframe() {
        el = $('body', $('iframe').contents());
        if (el.length != 1) {
          setTimeout(manipIframe, 100);
          return;
        }
        el.html('Hello World!');
      }
      manipIframe();
    });
    

    이 호출은 iframe 페이지에 코드를 필요로하지 않습니다. 상위 프레임 / 창에서 모든 코드가 상주하고 실행합니다.


  3. 3.의 iframe에서 나는 보통 블록의 끝까지 작은 스크립트를 넣어이 문제를 해결 :

    의 iframe에서 나는 보통 블록의 끝까지 작은 스크립트를 넣어이 문제를 해결 :

    <body>
    The content of your IFrame
    <script type="text/javascript">
    //<![CDATA[
       fireOnReadyEvent();
       parent.IFrameLoaded();
    //]]>
    </script>
    </body>
    

    나를 위해이 작품 대부분의 시간을. 때로는 가장 간단하고 순진 솔루션은 가장 적절한이다.


  4. 4.DrJokepu의 데이비드 머독 생각에 따라 내가 더 완전한 버전을 구현했습니다. 그것은 당신의 통제로 부모 및 iframe과 iframe이 모두 jQuery를 필요로한다.

    DrJokepu의 데이비드 머독 생각에 따라 내가 더 완전한 버전을 구현했습니다. 그것은 당신의 통제로 부모 및 iframe과 iframe이 모두 jQuery를 필요로한다.

    은 iframe 코드 :

    var iframe = window.frameElement;
    
    if (iframe){
        iframe.contentDocument = document;//normalization: some browsers don't set the contentDocument, only the contentWindow
    
        var parent = window.parent;
        $(parent.document).ready(function(){//wait for parent to make sure it has jQuery ready
            var parent$ = parent.jQuery;
    
            parent$(iframe).trigger("iframeloading");
    
            $(function(){
                parent$(iframe).trigger("iframeready");
            });
    
            $(window).load(function(){//kind of unnecessary, but here for completion
                parent$(iframe).trigger("iframeloaded");
            });
    
            $(window).unload(function(e){//not possible to prevent default
                parent$(iframe).trigger("iframeunloaded");
            });
    
            $(window).on("beforeunload",function(){
                parent$(iframe).trigger("iframebeforeunload");
            });
        });
    }
    

    부모 테스트 코드 :

    $(function(){
        $("iframe").on("iframeloading iframeready iframeloaded iframebeforeunload iframeunloaded", function(e){
            console.log(e.type);
        });
    });
    

  5. 5.문제에 대한 해결책을 발견.

    문제에 대한 해결책을 발견.

    당신은 iframe 대응을 열고 Thickbox와 링크를 클릭하면 TB_iframeContent의 ID로 iframe을 삽입합니다.

    대신 $ (문서) iframe이 코드에서 .ready 이벤트에 의존, 난 그냥 부모 문서에 iframe 대응의로드 이벤트에 바인딩 할 수 있습니다 :

    $('#TB_iframeContent', top.document).load(ApplyGalleria);
    

    이 코드는 상위 문서에서 컨트롤의 이벤트에 iframe을하지만, 바인딩입니다. 그것은 파이어 폭스와 IE에서 작동합니다.


  6. 6.기본적으로 무엇을 다른 사람이 이미 게시했지만 이럴 조금 청소기 :

    기본적으로 무엇을 다른 사람이 이미 게시했지만 이럴 조금 청소기 :

    $('<iframe/>', {
        src: 'https://example.com/',
        load: function() {
            alert("loaded")
        }
    }).appendTo('body');
    

  7. 7.이 시도,

    이 시도,

    <iframe id="testframe" src="about:blank" onload="if (testframe.location.href != 'about:blank') testframe_loaded()"></iframe>
    

    당신이 다음 할 필요가 testframe_loaded 자바 스크립트 함수를 만드는 것입니다 ().


  8. 8.나는 브라우저 캐시로 jQuery를 아약스와 PDF를로드하고 있습니다. 그 때 나는 이미 브라우저 캐시에 데이터가 포함 된 요소를 만들 수 있습니다. 나는 너무 iframe이 작동합니다 같아요.

    나는 브라우저 캐시로 jQuery를 아약스와 PDF를로드하고 있습니다. 그 때 나는 이미 브라우저 캐시에 데이터가 포함 된 요소를 만들 수 있습니다. 나는 너무 iframe이 작동합니다 같아요.

    
    var url = "http://example.com/my.pdf";
    // show spinner
    $.mobile.showPageLoadingMsg('b', note, false);
    $.ajax({
        url: url,
        cache: true,
        mimeType: 'application/pdf',
        success: function () {
            // display cached data
            $(scroller).append('<embed type="application/pdf" src="' + url + '" />');
            // hide spinner
            $.mobile.hidePageLoadingMsg();
        }
    });
    

    당신은 제대로뿐만 아니라 당신의 HTTP 헤더를 설정해야합니다.

    
    HttpContext.Response.Expires = 1;
    HttpContext.Response.Cache.SetNoServerCaching();
    HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);
    HttpContext.Response.CacheControl = "Private";
    

  9. 9.이것은 내가 우리의 고객과 다 퉜다 정확한 문제였다. 나는 iframe을 준비하기위한 작업에 보이는 작은 jQuery 플러그인을 만들었습니다. 그것은 확인은 iframe이 "준비"사실인지 확인하기 위해 iframe이 소스와 함께 내부 문서 URL과 결합 된 iframe이 문서 readyState가를 확인하기 위해 폴링을 사용합니다.

    이것은 내가 우리의 고객과 다 퉜다 정확한 문제였다. 나는 iframe을 준비하기위한 작업에 보이는 작은 jQuery 플러그인을 만들었습니다. 그것은 확인은 iframe이 "준비"사실인지 확인하기 위해 iframe이 소스와 함께 내부 문서 URL과 결합 된 iframe이 문서 readyState가를 확인하기 위해 폴링을 사용합니다.

    "온로드"의 문제는 당신이 당신이하지 않을 수 있습니다 다음 캐시 경우 iframe이 로딩을 잡으려고 시도 할 필요가 후하지 않는 경우는 DOM에 추가되는 실제 iframe이에 액세스 할 필요가 있다는 것입니다. 내가 필요하면 언제든지 호출 할 수있는 스크립트, 그리고 iframe이가 "준비"이었다 아닌지 여부를 결정합니다.

    여기에 질문입니다 :

    지역은 iframe로드 여부를 결정하기위한 성배

    여기에 내가 결국 해낸 jsfiddle입니다.

    https://jsfiddle.net/q0smjkh5/10/

    그것은 위키 피 디아 지적 있기 때문에 크로스 도메인을해야하는 - -, 나는 다음은 iframe을 확인하면서 DOM에 iframe을 추가하도록 온로드 기다리고 위의 jsfiddle에서 내부 문서의 준비 상태입니다하지만 크롬은 "완전한"보고 보인다. iframe이 사실 준비가되면 플러그인의 iready 방법은 다음 호출됩니다. 콜백은 다시 내부 문서의 준비 상태를 확인하려고 - 이번에는 크로스 도메인 요청을 (정확하다)을보고 - 어쨌든 내가 필요하고 다른 사람을 도움이되기를 바랍니다 무엇을 위해 작동하는 것 같다.

    <script>
      (function($, document, undefined) {
        $.fn["iready"] = function(callback) {
          var ifr = this.filter("iframe"),
              arg = arguments,
              src = this,
              clc = null, // collection
              lng = 50,   // length of time to wait between intervals
              ivl = -1,   // interval id
              chk = function(ifr) {
                try {
                  var cnt = ifr.contents(),
                      doc = cnt[0],
                      src = ifr.attr("src"),
                      url = doc.URL;
                  switch (doc.readyState) {
                    case "complete":
                      if (!src || src === "about:blank") {
                        // we don't care about empty iframes
                        ifr.data("ready", "true");
                      } else if (!url || url === "about:blank") {
                        // empty document still needs loaded
                        ifr.data("ready", undefined);
                      } else {
                        // not an empty iframe and not an empty src
                        // should be loaded
                        ifr.data("ready", true);
                      }
    
                      break;
                    case "interactive":
                      ifr.data("ready", "true");
                      break;
                    case "loading":
                    default:
                      // still loading
                      break;   
                  }
                } catch (ignore) {
                  // as far as we're concerned the iframe is ready
                  // since we won't be able to access it cross domain
                  ifr.data("ready", "true");
                }
    
                return ifr.data("ready") === "true";
              };
    
          if (ifr.length) {
            ifr.each(function() {
              if (!$(this).data("ready")) {
                // add to collection
                clc = (clc) ? clc.add($(this)) : $(this);
              }
            });
            if (clc) {
              ivl = setInterval(function() {
                var rd = true;
                clc.each(function() {
                  if (!$(this).data("ready")) {
                    if (!chk($(this))) {
                      rd = false;
                    }
                  }
                });
    
                if (rd) {
                  clearInterval(ivl);
                  clc = null;
                  callback.apply(src, arg);
                }
              }, lng);
            } else {
              clc = null;
              callback.apply(src, arg);
            }
          } else {
            clc = null;
            callback.apply(this, arguments);
          }
          return this;
        };
      }(jQuery, document));
    </script>
    

  10. 10.이 답변에서이 기능은 $가 .ready 명시 적으로 iframe을 실패로이 문제를 해결할 수있는 가장 좋은 방법입니다. 다음은이 기능을 지원하지 않는 결정이다.

    이 답변에서이 기능은 $가 .ready 명시 적으로 iframe을 실패로이 문제를 해결할 수있는 가장 좋은 방법입니다. 다음은이 기능을 지원하지 않는 결정이다.

    iframe이 이미로드 된 경우로드 이벤트는 발생하지 않습니다. 아주이 2020 년 문제가 남아 좌절!

    function onIframeReady($i, successFn, errorFn) {
        try {
            const iCon = $i.first()[0].contentWindow,
            bl = "about:blank",
            compl = "complete";
            const callCallback = () => {
                try {
                    const $con = $i.contents();
                 if($con.length === 0) { // https://git.io/vV8yU
                    throw new Error("iframe inaccessible");
                 }
    
    
       successFn($con);
         } catch(e) { // accessing contents failed
            errorFn();
         }
      };
      const observeOnload = () => {
        $i.on("load.jqueryMark", () => {
            try {
                const src = $i.attr("src").trim(),
                href = iCon.location.href;
                if(href !== bl || src === bl || src === "") {
                    $i.off("load.jqueryMark");
                    callCallback();
                }
            } catch(e) {
                errorFn();
            }
        });
      };
      if(iCon.document.readyState === compl) {
        const src = $i.attr("src").trim(),
        href = iCon.location.href;
        if(href === bl && src !== bl && src !== "") {
            observeOnload();
        } else {
            callCallback();
        }
      } else {
        observeOnload();
      }
    } catch(e) {
        errorFn();
    }
    

    }

  11. from https://stackoverflow.com/questions/205087/jquery-ready-in-a-dynamically-inserted-iframe by cc-by-sa and MIT license