Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension - Content Script unable to find elements by class name

I am attempting to access elements with a specific class name from a page using a content script of a Chrome extension. So far the content script can successfully find an element with a specific id using document.getElementById(), but using document.getElementsByClassName() or jQuery's $(".className") yields no results. For the sake of testing, I used 'header' as my class name and every website I ran the extension on resulted in an array length of 0. Any ideas what I might be missing? Here's what I have been testing with:

manifest.json
=================
{
    "name": "Sample Extension",
    "version": "0.0.1",
    "description": "Sample extension",
    "icons": {"128": "icon.png"},
    "permissions": [
        "tabs", "<all_urls>"
    ],
    "browser_action": {
        "default_icon": "browseraction.png",
        "default_title": "Sample",
        "popup": "popup.html"
    },
    "content_scripts": [
        {
            "matches": [ "<all_urls>" ],
            "js": ["scripts/contentscript.js"],
            "run_at": "document_end"
        }
    ]
}

contentscript.js
===================
var elems = document.getElementsByClassName("header");
alert( elems.length );
like image 944
sojo2600 Avatar asked Dec 30 '25 00:12

sojo2600


1 Answers

Your code is very basic and straightforward, it can't be a cause of problem. In fact, I just used your exact code (with "says" class and website you provided) and alert() says every and each time 1 (which is correct).

My best guess is that you haven't reloaded your extension after making changes in contentscript.js OR some other extension is interfering and causing this strange behavior. Try disabling other extensions before testing your extension.

like image 50
Konrad Dzwinel Avatar answered Dec 31 '25 17:12

Konrad Dzwinel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!