2017-03-16 5 views
1

이 JS 코드를 고려하십시오. 그것은 기본적으로 CKEditor 인스턴스를 초기화 1 초 대기 후 codeToDebugiframe 내부에서 DOM 요소의 프로토 타입 확장

function codeToDebug(){ 
    setNodeListProp("attr", function customAttr(name, val){ 
     if(typeof val != "undefined"){ 
      this.setAttribute(name, val); 
      return this; 
     } 
     else return this.getAttribute(name); 
    }); 

    // secondary check: all elements on the current document HAVE `attr` method 
    var all = document.querySelectorAll("*"); 
    for(var i = 0, len = all.length;i < len; i++) 
     if(!all[i].attr) // always false 
      console.dir(all[i]); // never executes 

    // logs undefined 
    console.log(
      document.querySelector(".cke_wysiwyg_frame") 
       .contentDocument 
       .querySelector(".cke_editable").attr); 
} 

window.onload = function(){ 
    // Replace the <textarea id="editor1"> with a CKEditor 
    // instance, using default configuration. 
    CKEDITOR.editorConfig = function (config) { 
     config.language = 'es'; 
     config.uiColor = '#F7B42C'; 
     config.height = 300; 
     config.toolbarCanCollapse = true; 

    }; 
    CKEDITOR.replace('editor1'); 
    // wait for async editor to load 
    setTimeout(codeToDebug, 1000); 
}; 

function setNodeListProp(prop, func){ 
    // in case of custom created array of Nodes, Array.prototype is necessary 
    Array.prototype[prop] = NodeList.prototype[prop] = function() { 
     var args = [].slice.call(arguments, 0); 
     this.forEach(function(node) { 
      func.apply(node, args); 
     }); 
     return this; 
    }; 

    Node.prototype[prop] = func; 
} 

방법 codeToDebugattr 방법으로 NodeNodeList의 원형 연장 달린다. 그런 다음 log s이면 attr이 CKEditor의 iframe 안에있는 .cke_editable 텍스트 영역에 있습니다. 놀랍게도, 그것은 undefined을 기록합니다.


내 질문 : 내가 주 문서에 확장하고 때

  1. 왜 iframe을 내부 Node의의 프로토 타입이 확장되지 않는 이유는 무엇입니까? (모든 요소가 공유하는 공통의 글로벌 Node하지? - 상관없이 어디에) - 그 iframe을에서, 웹 페이지 문서에 존재 모든 요소의 DOM을 확장하는 가장 좋은 방법은 무엇
  2. , 그리고 더 중첩 된 iframe?

주 :

  1. 이미 DOM을 확장와 Kangax의 기사 (및 프로토 타입의 버그를) 읽었습니다. 하지만 유스 케이스는 완전히 다릅니다. 나는 Chrome과 Opera의 최신 버전 (Webkit 모두)을 지원하기로되어 있습니다. 그렇기 때문에 충돌에 대해 걱정할 필요가 없습니다. 따라서 프로토 타입을 확장하는 데 따른 위험을 감수했음을 확신합니다. 그러나이 질문은 그 문제가 아닙니다.

  2. 여기 (JSBin 또는 코드 조각은 CKEditor를 표시하지 않습니다 어떤 이유로)를 HTML의 : <script src="https://cdn.ckeditor.com/4.5.1/standard/ckeditor.js"></script><script>..ABOVE_JS_CODE..</script><textarea name="editor1" id="editor1" rows="10" cols="80"></textarea>

+0

iFrame을 만들면 다른 창과 동일하게 작동하므로 자체 범위가 초기화됩니다. 그것이 아닌 다른 범위의 오버라이드는 영향을 미치지 않습니다. 또한 선택기를 수락하고이를 사용하여 반복 할 수있는 자체 라이브러리를 사용할 수 있습니다. 프로토 타입을 재정의하는 좋은 방법은 변화하는 브라우저이기 때문에 불일치를 유발하는 유사한 동작을 시작하는 것입니다. – Rajesh

답변

0

그래서, 자신이이 문제를 해결하는 기능을 썼다 (I는 로컬 index.html를 생성). 유사한 솔루션을 찾는 사람들에게 도움이 될 수 있습니다. 그들은이 작업을 달성하기 위해 더 나은 더 적절한 방법을했다고 생각하면

function initiateIframeCheck(parentDoc){ 
    var iframes = parentDoc.querySelectorAll("iframe"), 
     win, doc; 

    iframes.forEach(function(iframe){  
     try{     
      doc = iframe.contentDocument; 
      win = iframe.contentWindow; 

      // make sure handler's not already attached 
      if(!doc[UNIQ_KEY]){ 
       doc[UNIQ_KEY] = true; 
       updateAllValuesPerWin(win);  
       setInterval(initiateIframeCheck, IFRAME_CHECK_TIMER, doc); 
      } 
     }catch(e){ // CORS 
      //console.dir(e);    
     } 
    }); 
} 

누군가가 답변을 게시하시기 바랍니다 :

(function protoExtensionWork(){ 
    window.updateAllValuesPerWin = function(win){  
     for(var i = 0, count = protoExtensionNames.length; i < count; i++) 
      setNodeListPropPerWindow(protoExtensionNames[i], protoExtensionFunctions[i], win); 
    }; 

    // fill this up as per your requirement 
    var protoExtensionNames = [], protoExtensionFunctions = []; 

    function setNodeListPropPerWindow(prop, func, win){ 
     // in case of custom created array of Nodes, Array.prototype is necessary 
     win.Array.prototype[prop] = win.NodeList.prototype[prop] = function() { 
      var args = [].slice.call(arguments, 0); 
      this.forEach(function(node) { 
       func.apply(node, args); 
      }); 
      return this; 
     }; 

     win.Node.prototype[prop] = func;  
    } 
})(); 

이것은 iframe의를 찾고에 대한 코드의 두 번째 작품이다.