简体   繁体   中英

Use JQuery in an inject.js file executed under background.js

I am building a chrome extension where my background.js script file will execute inject.js script file on a certain event.

I also have a local jquery.min.js file which I have included in my manifest.json file so that I can use it in my background.js file.

"background": {
    "scripts": ["jquery.min.js","background.js"]
  },

However, I am not sure how can use jquery in my inject.js file. I tried using /// <reference path="jquery.min.js" /> but that didn't work.

Any thoughts on how can I use jquery and other js libraries in my inject.js ?

Below if my background.js code

chrome.browserAction.onClicked.addListener(function(tab) {
    //To verify if jQuery is working  
    if (jQuery) {
        console.log("Jquery on");
    } else {
        console.log("Jquery off");
    }

    if(activeTabs.length===0){
        chrome.tabs.executeScript(tab.id, {file:"js/inject.js"});
    }
}

You have to inject jquery.min.js before injecting inject.js . In your case:

if(activeTabs.length===0){
    chrome.tabs.executeScript(tab.id, {file:'jquery.min.js'},function(){
        chrome.tabs.executeScript(tab.id, {file:'js/inject.js'});
    });
}

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