简体   繁体   English

在 Chrome 扩展脚本之间共享功能的最佳方式是什么?

[英]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.我在 background.js 中定义了一个 function,我在 background.js 中使用它。 I also want to use that function in options.html's options.js without rewriting it there.我还想在 options.html 的 options.js 中使用 function 而不在那里重写它。 I know I can do chrome.extension.getViews() to get the global objects of other extension scripts.我知道我可以做 chrome.extension.getViews() 来获取其他扩展脚本的全局对象。 I can also send a message from options.js and have background.js run the function with data from options.js.我还可以从 options.js 发送一条消息,并让 background.js 使用来自 options.js 的数据运行 function。 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).要在 background.js 和 options.js 文件中使用 function,您需要创建第三个文件以将 function 抽象为(我将使用 helper.js 作为示例)。 After the function is abstracted you can use the export statement which will allow it to be importable by the background and options scripts.在 function 被抽象出来后,您可以使用 export 语句,这将允许后台和选项脚本导入它。

Helper.js:助手.js:

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

background script:背景脚本:

import { reusableFunction } from './helper.js';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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