简体   繁体   中英

Google Chrome Extension include Jquery and another custom javascript file

I'm new to making Chrome Extensions. So I don't know where to start. Tried looking for answers but they don't answer mine.

So basically I need JQuery and also my own custom javascript file(customfile.js) to be executed at the same time whenever a user clicks on my extension icon. The customfile will use the JQuery functions from the JQuery file to call an ajax api.

This is my manifest.json.

{
  "manifest_version": 2,

 "name": "Example",
  "description": "Example",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Click here!"
  },
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["jquery-3.2.1.min.js","customfile.js"],
    "persistent": false
  },
     "content_scripts": [ {
    "js": [ "jquery-3.2.1.min.js", "customfile.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }]
}

For some reason some developers left out the "background", and some left out the "content_scripts". Which is correct, or do I need both?

Also, I've read about programmatic injection. Is my code correct in such a way that it will only run both files when only needed? Where do I put this code into, my customfile.js or jquery.js?

chrome.tabs.executeScript(null, { file: "jquery-3.2.1.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "customfile.js" });
});

You need to set the content_scripts property or use chrome.tabs.executeScript if you want to inject code in web pages. It seems that you're not looking for that, you only need a background script.

And to respond to icon clicks, add this listener to one of your background scripts:

chrome.browserAction.onClicked.addListener(function(){
      ....
});

HERE you can find the documentation for the manifest. It explain what each property in the manifest file does.

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