简体   繁体   中英

What is the best way to share functions between Chrome extension scripts?

I have a function defined in background.js that I use inside of background.js. I also want to use that function in options.html's options.js without rewriting it there. I know I can do chrome.extension.getViews() to get the global objects of other extension scripts. I can also send a message from options.js and have background.js run the function with data from options.js. Is there an another method? More importantly, is one preferred over the other?

To use the function in the background.js and options.js files you need to create a 3rd file to abstract the function into (I will use helper.js for the example). After the function is abstracted you can use the export statement which will allow it to be importable by the background and options scripts.

Helper.js:

export function reusableFunction () {
  // your code here
}

background script:

import { reusableFunction } from './helper.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