Can I share code between different parts of Chrome Extension?

后端 未结 2 2234
天命终不由人
天命终不由人 2021-02-19 17:58

Let\'s say, I have a function:

var rand = function(n) {
    return Math.floor(Math.random() * n);
}

Can I use this function in both Content Scr

2条回答
  •  清酒与你
    2021-02-19 19:02

    Yes, you can, by putting it in a separate JS file and loading it in both.

    Say, you have a file utils.js that contain all such functions.

    Then you can load the background page like this:

    "background": {
      "scripts": [ "utils.js", "background.js" ]
    },
    

    And the content script like this:

    "content_scripts": [
      {
        "matches": ["..."],
        "js": ["utils.js", "content.js"]
      }
    ],
    

    Or, if you're using programmatic injection, chain the calls like this:

    chrome.tabs.executeScript(tabId, {file: "utils.js"}, function(){
      chrome.tabs.executeScript(tabId, {file: "content.js"}, yourActualCallback);
    });
    

提交回复
热议问题