[英]chrome extension: run script after page has finished loading javascript
[英]Running javascript in the Google Chrome extension after a page has done loading
我定位的網站幾乎是一個Javascript應用程序。 因此,我需要在所有內容加載完成后添加HTML。 我嘗試使用MutationObserver,但仍嘗試過早執行javascript,並且收到以下錯誤代碼`Uncaught TypeError:無法讀取未定義的屬性'appendChild'
我的密碼
的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);
}
<body>
<script type="text/javascript" src="/js/module/appMain.js?__=wfDkO"></script>
</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);
}
在我們的插件中,我們有類似
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);
}
}
這是在使用Selenium進行ui測試期間通常使用的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.