1

I want to inject jQuery into a web page (with a content script) in a Chrome extension.

I try, but something confuses me.

here is my manifest.json:

{
    "name": "test",
    "description": "test content script.",
    "version": "0.0.1",
    "background": {
        "scripts": ["jquery-1.10.2.js", "popup.js"]
    },
    "permissions": ["tabs", "notifications", "http://*/*", "https://*/*"],
    "browser_action": {
        "default_title": "test",
        "default_icon": "icon.png"
    },
    "options_page": "manage.html",
    "content_scripts": [
        {
            "matches": ["http://*/*", "https://*/*"],
            "js": ["jquery-1.10.2.js"]
        }
    ],
    "manifest_version": 2
}

jquery-1.10.2.js:

 /*jquery's orign code*/
  console.log("end of jquery");

I can see the console message but I still can't use jQuery.

I wrote a simple website and tried to include jQuery through the content script instead of adding it with a <script> tag.

In the Dev Tool console, I enter window.jQuery or $("li").siblings().

If include jQuery in the page, it works, but if it's injected with a content script, it shows jQuery as undefined.

Why does this happen?

Xan
  • 74,770
  • 16
  • 179
  • 206
mirtac
  • 13
  • 4

2 Answers2

2

I used this and it's working fine. maybe the path of your jquery is not correct.

"content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["js/jquery.min.js", "js/socket/socket.io.js","js/socket/client.js"],
    "run_at": "document_idle"
}]
aldesabido
  • 1,268
  • 2
  • 17
  • 38
  • I add console.log("end of jquery") at the end of jquery file,it work (pirnt at console of web page) but jquery's method can't use – mirtac Jan 29 '15 at 08:59
1

The situation is very similar to this question.

Content scripts live in their own, isolated JavaScript context. This is done so that scripts added by extensions don't coflict with the page or each other.

When you open the Dev Tools console, it shows console messages from all contexts of the webpage: page's context, contexts of the iframes (which are also isolated) and content script contexts. That's why you see the log message.

However, while it can show all messages at once, if you try to execute something, it must go to one context. By default, it's the page's context: <top frame> just above the console.

To execute something in the extension's context, you need to switch to it:

Switching context

And if you want to make some JavaScript available to the page context, you need to inject it into the page itself as a <script> tag. See this question.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206