Use existing jQuery in Chrome extension content sc

2019-09-10 05:06发布

问题:

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?

回答1:

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