2017-10-16 297 views
0

我針對的網站幾乎是一個Javascript應用程序。所以我需要在加載完成後添加HTML。我試着用MutationObserver,但它仍試圖過早執行JavaScript和我碰到下面的錯誤代碼`遺漏的類型錯誤:無法讀取屬性「的appendChild」的未定義頁面加載完成後在Google Chrome瀏覽器擴展中運行javascript

我的代碼

manifest.json的

{ 
    "manifest_version": 2, 

    "name": "Test", 
    "version": "1.0", 
    "description": "Test Description", 

    "content_scripts": [{ 
    "js": ["content.js"], 
    "run_at" : "document_idle", 
    "matches": ["https://pastvu.com/p/*"] 
    }] 

} 

content.js

new MutationObserver(function(mutations, observer) { 
    addHtml(); 
    observer.disconnect(); 
}).observe(document.querySelector('body'), {childList: true}); 


function addHtml(){ 

    var newDiv = document.createElement("div"); 
    newDiv.setAttribute("class","tltp-wrap"); 

    var newLink = document.createElement('a'); 
    newLink.setAttribute('href','http://www.google.com'); 

    var linkButton = document.createElement('span'); 
    linkButton.setAttribute('class','glyphicon glyphicon-map-marker'); 

    newLink.appendChild(linkButton); 
    newDiv.appendChild(newLink); 

    document.getElementsByClassName("toolsBtm")[0].appendChild(newDiv); 
} 

Here is the我針對的頁面。正如你可以看到這樣

<body> 
    <script type="text/javascript" src="/js/module/appMain.js?__=wfDkO"></script> 
</body> 

<body>看起來我的目標是要等到身體負荷的html或至少unitil .toolsBtm DIV存在。

我改變content.js這和仍然沒有運氣

new MutationObserver(function(mutations, observer) { 
    var bodyLoaded = document.getElementsByClassName('toolsBtm'); 
    if (bodyLoaded.length > 0) { 
     alert('a'); 
     addHtml(); 
    } 
}).observe(document.querySelector('body'), {childList: true}); 


function addHtml(){ 

    var newDiv = document.createElement("div"); 
    newDiv.setAttribute("class","tltp-wrap"); 

    var newLink = document.createElement('a'); 
    newLink.setAttribute('href','http://www.google.com'); 

    var linkButton = document.createElement('span'); 
    linkButton.setAttribute('class','glyphicon glyphicon-map-marker'); 

    newLink.appendChild(linkButton); 
    newDiv.appendChild(newLink); 

    document.getElementsByClassName("toolsBtm")[0].appendChild(newDiv); 
} 
+0

您是否嘗試過使用''run_at「:」document_end「'? –

+0

@FiriceNguyen'document_end'不晚於'document_idle'。 – Xan

+0

@FiriceNguyen是的,我做了 –

回答

1

在我們的插件,我們有一些像

export function invokeAfterDomIsReady(context = document, selector, time = 400, func) { 
    const domEl = context.querySelector(selector); 
    if (domEl != null) { 
     func(domEl); 
    } else { 
     setTimeout(function() { 
      invokeAfterDomIsReady(context, selector, time, func); 
     }, time); 
    } 
} 

這是一些與硒的UI測試期間所常用。

相關問題