简体   繁体   中英

I'm trying to get jquery working in the background.js of my chrome extension and it won't work. why?

I've read up on quite a few stack overflow questions about jQuery and background pages and simply do not understand the rules of engagement. I don't know how they interact. Can somebody tell me why this code does not work?

manifest.json

{
  "name": "test 1",
  "description": "testing jquery",
  "version": "2.0",
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": [ "jquery-2.1.1.js", "background.js"],
    "persistent": false
  },
  "browser_action": {
     "default_title": "test"
  },
  "manifest_version": 2
}

i don't forget to include the jQuery file when i upload the extension

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(
    { code: 'console.log("this works");'},
    { code: '$( document ).ready(function() { console.log( "but this does not work :(" ); });' }
  );
});

keep in mind i'm familiar with how to use jQuery using content scripts but the problem with these is then the

chrome.****** 

commands don't work.

Please help!

You are correctly loading jQuery into the background page. If you were to use $(document).ready() in its code, it would work.

The problem is, when you use executeScript , the code you specify does not execute in the same context as background.js . A brand new JS context is created, attached to the tab in question, and that context does not have jQuery in it (even if the tab's context itself has it, by the way, see isolated context ).

Furthermore, you're calling executeScript wrong. Its arguments are:

  • integer (optional) tabId
  • object details
  • function (optional) callback

You are calling it with two objects; it doesn't work like that.


So, to fix, you will need to inject jQuery first in that execution context, and then your code. You need to chain 2 calls to ensure they execute in the correct order.

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(
    tab.id,
    { file: 'jquery-2.1.1.js' },
    function() {
      chrome.tabs.executeScript(
        tab.id,
        { code: '$( document ).ready(function() { console.log( "This works now" ); });' }
      );
    }
  );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM