1

Everything I find seems to involve injecting jQuery, but I know jQuery already exists on the page (the browser JS console lets me use it).

I have a background script that is sending a message to my content script, which is running the function. When that function executes I get:

Error in event handler for runtime.onMessage: ReferenceError: jQuery is not defined

(I've tried both $ and jQuery references)

Any ideas why I cannot access the existing jquery object from the content script?

Kaitlyn2004
  • 3,879
  • 4
  • 16
  • 16
  • If you inject code into the webpage, your code needs to wait on jquery init, then it should work. But if you try to use the jquery from a page in your extension code, it won't work because chrome doesn't share the webpage scripts with your extension. – SEUH Apr 30 '16 at 16:11
  • Possible duplicate of [How to use jQuery in chrome extension?](http://stackoverflow.com/questions/21317476/how-to-use-jquery-in-chrome-extension) – Zig Mandel Apr 30 '16 at 18:10
  • @ZigMandel Disagree with the duplicate. – Xan Apr 30 '16 at 22:58
  • @xan why? this case is covered on that dup. its a common jquery dup. – Zig Mandel May 01 '16 at 12:42
  • @ZigMandel The question is about "why can't page's version be used", not "how I use jQuery in a content script". Why, not how. – Xan May 01 '16 at 14:44
  • @xan aha, I linked to the wrong one but Im sure there is more than one existing answer explaining why its not there and the difference with injecting a script vs content – Zig Mandel May 01 '16 at 14:46

1 Answers1

3

This is because content scripts by design are not allowed to access variables/functions defined by the page

https://developer.chrome.com/extensions/content_scripts

However, content scripts have some limitations. They cannot:

  • Use chrome.* APIs, with the exception of:
    • extension ( getURL , inIncognitoContext , lastError , onRequest , sendRequest )
    • i18n
    • runtime ( connect , getManifest , getURL , id , onConnect , onMessage , sendMessage )
    • storage
  • Use variables or functions defined by their extension's pages
  • Use variables or functions defined by web pages or by other content scripts

So if you wish to use a certain library your extension has to inject it

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
  • Hmm thanks, that's helpful. I added a local jquery to the content_scripts in manifest, and now I can add a div to the dom on document ready, but when I click a button from my extension popup which sends a message to execute a function in that same content script, it still complains jquery and $ don't exist. Is this somehow related to the last points? Even though it's a content script, since it's coming from a message from the background JS... it's missing context? – Kaitlyn2004 Apr 30 '16 at 16:26
  • @Kaitlyn Hard to say from your explanation; at this point a new question is probably better. – Xan Apr 30 '16 at 22:57