Michael Spector
Michael Spector

Reputation: 37019

Chrome extension content scripts are not injected in the first place, how to debug?

When I'm running the Chromium browser using:

chromium-browser --load-extension=/path/to/my/extension --user-data-dir=/path/to/chrome/profile --app=http://localhost/somepage

some content scripts are not injected into the page. These scripts are defined as follows in the manifest file:

"content_scripts" : [{
                "matches" : [ "http://*/*", "https://*/*" ],
                "js" : [ "content/s1.js", "content/s2.js", "content/s3.js", "content/s4.js" ],
                "run_at" : "document_end"
}]

When inspecting the page, I see that only s1.js and s4.js were injected successfully. After reloading the page all scripts are injected correctly, and my extension works as expected.

What can be the reason for that, and how to debug this?

Edit:

Those content scripts (that fail to inject sometimes) reference 'document' at the beginning. It seems like if I wrap them into something like:

setTimeout(function() { document. ... }, 5000);

They are always injected as expected. Is it possible that the document is not available, even though "run_at": "document_end" was specified in manifest?

Thanks!

Upvotes: 2

Views: 2524

Answers (1)

user1731468
user1731468

Reputation: 1000

You can better do this:

Create 1 content.js script:

/* inject script */
try {
var script1 = document.createElement("script");script1.type = "text/javascript";script1.src = chrome.extension.getURL("/js/injected1.js");document.getElementsByTagName("head")[0].appendChild(script1);
var script2 = document.createElement("script");script2.type = "text/javascript";script2.src = chrome.extension.getURL("/js/injected2.js");document.getElementsByTagName("head")[0].appendChild(script2);
var script3 = document.createElement("script");script3.type = "text/javascript";script3.src = chrome.extension.getURL("/js/injected3.js");document.getElementsByTagName("head")[0].appendChild(script3);
var script4 = document.createElement("script");script4.type = "text/javascript";script4.src = chrome.extension.getURL("/js/injected4.js");document.getElementsByTagName("head")[0].appendChild(script4);
} catch(e) {}

in the manifest.json:

"content_scripts" : [{
            "matches" : [ "http://*/*", "https://*/*" ],
            "js" : [ "content.js" ],
            "run_at" : "document_end"

}]

Upvotes: 1

Related Questions