Chrome扩展程序Javascript无法正常运行

时间:2014-09-16 05:50:01

标签: javascript google-chrome google-chrome-extension

我尝试在纯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扩展程序时还有其他事可做吗?&#39;

继承我的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

2 个答案:

答案 0 :(得分:1)

好吧,我在你的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"
  }
}

我更改了permissionsmatches部分。

答案 1 :(得分:0)

找到解决方案。问题是DOM没有完全加载,因此在DOM加载之前执行的脚本无法正确获取数据是我猜的。

我尝试使用

document.onload=function(){}

window.onload=function(){}

window.onload在获取输出时遇到问题,而document.onload从未触发过。

所以,尝试使用延迟:

setTimeout(function(){
      <javascript code>
},3000);

这很好用。不确定它是否是最好的方法。

作为替代方案,将jquery添加到扩展名并使用:

$(document).ready(function(){
      <javascript code>
});

这样做效果更好。

相关问题