Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome content_script: How to wait for jQuery

I'm writing a small Chrome extension that would have a content_script.

It would run on a single domain, I'm trying to improve a site a bit.

I want to use jQuery in my content script, but the site also uses jQuery, so I cannot simply add jQuery to my extension's content_script array.

My content_script will

"run_at": "document_end"

but jQuery is not yet loaded. It's not loaded on document_idle either.

So I have to wait for it.

How do I do that?

I've tried doing this:

(function() {
    var i = setInterval(function () {
        console.log(typeof jQuery + " " + i);
        if (typeof jQuery != "undefined") {
            console.log("jQuery loaded");
            clearInterval(i);
        } else {
            console.log("jQuery not loaded");
        }
    }, 200);
})();

But for some reason typeof jQuery is always undefined within that loop.

If I manually clearInterval, and check typeof jQuery I properly get "function".
(chrome inspector console)

Any ideas?

EDIT: content_scripts are special:

Content scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.

like image 339
Prody Avatar asked Mar 29 '26 17:03

Prody


1 Answers

I cannot simply add jQuery to my extension's content_script array.

You can and should. Extension variable space is sandboxed, so content scripts cannot access variables from parent's page and vice versa.

like image 111
serg Avatar answered Apr 02 '26 22:04

serg