javascript
  • node.js
  • ecmascript-6
  • jsdom
  • es6-proxy
  • 2016-10-14 164 views 0 likes 
    0

    我需要攔截對某些DOM API函數的調用並將其參數存儲爲副作用。例如,假設我對函數getElementsByTagNamegetElementById感興趣。見下面的例子:攔截調用DOM API函數

    "use strict"; 
    const jsdom = require("jsdom"); 
    let document = jsdom.jsdom("<html><head></head><body><div id='foo'><div></div></div></body></html>"); 
    let cpool = {ids: [], tags: []}; 
    let obj = document.getElementById("foo"); 
    // --> cpool = {ids: ["foo"], tags: []} 
    obj.getElementsByTagName("div"); 
    // --> cpool = {ids: ["foo"], tags: ["div"]} 
    

    一個重要的注意的是,我使用Node.js的對象documentjsdom庫實現。到目前爲止,我試圖利用ES6代理修改上述DOM函數的行爲。

    這就是我試圖通過代理文檔對象來捕獲所有方法調用。我想知道是否以及如何使用這種技術或其他方法,我可以解決我的問題。

    let documentProxy = new Proxy(document, { 
        get(target, propKey, receiver) { 
         return function (...args) { 
          Reflect.apply(target, propKey, args); 
          console.log(propKey + JSON.stringify(args)); 
          return result; 
         }; 
        } 
    });  
    documentProxy.getElementById("foo"); 
    // --> getElementById["foo"] 
    
    +0

    我不知道爲什麼,但它聽起來就像你做了壞事... – evolutionxbox

    +0

    @evolutionxbox什麼叫'壞thing'是什麼意思? –

    +0

    你試圖通過攔截這些調用來解決什麼是你的[實際問題](http://meta.stackexchange.com/q/66377)? – Bergi

    回答

    0

    如果您只想攔截對這兩個函數的調用,則不需要使用代理服務器。您只需存儲原始函數的副本,然後使用保存參數的函數覆蓋要攔截調用的函數,然後調用原始函數。

    const cpool = {ids: [], tags: []} 
     
    
     
    ;(getElementsByTagNameCopy => { 
     
        document.getElementsByTagName = tag => { 
     
        cpool.tags.push(tag) 
     
        return Reflect.apply(getElementsByTagNameCopy, document, [tag]) 
     
        } 
     
    })(document.getElementsByTagName) 
     
    
     
    ;(getElementsByTagNameCopy => { 
     
        Element.prototype.getElementsByTagName = function(tag) { 
     
        cpool.tags.push(tag) 
     
        return Reflect.apply(getElementsByTagNameCopy, this, [tag]) 
     
        } 
     
    })(Element.prototype.getElementsByTagName) 
     
    
     
    ;(getElementByIdCopy => { 
     
        document.getElementById = id => { 
     
        cpool.ids.push(id) 
     
        return Reflect.apply(getElementByIdCopy, document, [id]) 
     
        } 
     
    })(document.getElementById) 
     
    
     
    console.log(document.getElementsByTagName('body')) 
     
    console.log(document.getElementById('whatever')) 
     
    console.log(document.body.getElementsByTagName('div')) 
     
    console.log(cpool)

    +0

    它只跟蹤文檔對象上的調用,而不是_Element_。例如這裏'console.log(document.getElementById('test')。getElementsByTagName('span'));'_span_不存儲在標籤中。 –

    +0

    @AlexElyasov看我的編輯。 –

    +0

    似乎不太可能覆蓋每個單獨的方法;只是說。 – naomik

    相關問題