简体   繁体   中英

Chrome Extension Javascript not working properly

I'm trying to write Chrome Extension in pure javascript to fetch a collection of nodes and make some changes to it. So, I started off with:

var list = document.getElementsByClassName("testclass");    
console.log(list);           //1
console.log(list.length);    //2
console.log(list[0]);        //3  

The output for this comes up as:

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

The same thing, which I give in jsfiddle , I get proper outputs:

1. HTMLCollection object with all elements and length: <no of elements> and __proto__: HTMLCollection
2. <no of elements>
3. First Element

Why am I unable to iterate when the javascript used is them same? Is there something else to do when we are using a Chrome extension?'

Heres my manifest.json in case it helps:

{
  "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"
  }
}

My javascript code is in testscript.js

Well, I did some modifications in your manifest file and it worked for me. Here is the updated version:

{
  "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"
  }
}

I have changed the permissions and matches sections.

Found a solution. The problem was that the DOM was not getting loaded fully, hence my script which executed before DOM got loaded, could not fetch data properly is what I am guessing.

I tried using

document.onload=function(){}

and

window.onload=function(){}

window.onload had trouble fetching the output, and document.onload never triggered at all.

So, tried using a delay:

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

And this works fine. Not sure if its the best method.

As an alternative, added jquery to the extension and used:

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

And this works even better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM