سؤال

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 );
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top