Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension content script not accessing page's DOM in which it is injected

I'm attempting to pull data from a page that a user is viewing and sending that data to the extension popup. I'm running into trouble extracting information from the current page. After reviewing the google code tutorials, I set up my manifest and content script as shown below. When I go to a test page, which has a span with id="comments", my variable from the injected content script always ends up as null. Anyone know what I could be missing? Thanks!

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": ["http://*/*", "<all_urls>" ],
            "js": ["scripts/contentscript.js"]
        }
    ]
}

contentscript.js
===================
var comments = document.getElementById("comments");
alert( comments.innerText );
like image 972
sojo2600 Avatar asked Jun 14 '12 18:06

sojo2600


Video Answer


1 Answers

It's possible the comments are loaded after the execution of your script.

Try to set this in the manifest :

        "run_at" : "document_end",

Or if you suspect an AJAX loading, call your code later with a setTimeout.

Of course the best scheme would depend on the precise page and its inner working.

like image 149
Denys Séguret Avatar answered Nov 15 '22 05:11

Denys Séguret