[英]Chrome Extension Javascript not working properly
我試圖用純JavaScript編寫Chrome擴展程序,以獲取節點集合並對其進行一些更改。 因此,我從開始:
var list = document.getElementsByClassName("testclass");
console.log(list); //1
console.log(list.length); //2
console.log(list[0]); //3
輸出結果為:
1. An object [item:function, namedItem:function], which has all the elements and a length: <number of elements> and __proto___: HTMLCollection (As Expected)
2. 0
3. undefined
我在jsfiddle中給出的同一件事,得到正確的輸出:
1. HTMLCollection object with all elements and length: <no of elements> and __proto__: HTMLCollection
2. <no of elements>
3. First Element
為什么使用的JavaScript相同時無法迭代? 當我們使用Chrome擴展程序時,還有其他事情要做嗎?”
繼承我的manifest.json以防萬一:
{
"manifest_version": 2,
"name": "Something",
"description": "Something something...",
"version": "1.0",
"permissions": [
"tabs",
"notifications",
"http://*/",
"https://*/"
],
"content_scripts": [{
"matches": ["https://*","http://*"],
"js": ["testscript.js"],
"run_at": "document_end"
}],
"web_accessible_resources": ["samplejs.js"],
"browser_action": {
"default_popup": "popup.html"
}
}
我的JavaScript代碼在testscript.js
好吧,我對您的manifest
文件做了一些修改,它對我有用。 這是更新的版本:
{
"manifest_version": 2,
"name": "Something",
"description": "Something something...",
"version": "1.0",
"permissions": [
"tabs",
"notifications",
"http://*/",
"http://*/*",
"https://*/*"
],
"content_scripts": [{
"matches": ["https://*/*", "http://*/*"],
"js": ["testscript.js"],
"run_at": "document_end"
}],
"web_accessible_resources": ["samplejs.js"],
"browser_action": {
"default_popup": "popup.html"
}
}
我更改了permissions
和matches
。
找到了解決方案。 問題是DOM尚未完全加載,因此我猜測的是在DOM加載之前執行的腳本無法正確獲取數據。
我嘗試使用
document.onload=function(){}
和
window.onload=function(){}
window.onload在獲取輸出時遇到問題,document.onload從未觸發過。
因此,嘗試使用延遲:
setTimeout(function(){
<javascript code>
},3000);
這很好。 不確定是否是最好的方法。
或者,將jquery添加到擴展中並使用:
$(document).ready(function(){
<javascript code>
});
而且效果更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.