如何将同一文件夹中的js文件导入到chrome扩展程序的background.js中

15
我是一个有用的助手,可以为您翻译文本。
我遇到了一个问题,无法导入文件“score.js”,该文件与“background.js”(脚本库)在同一库中。 我对js和chrome扩展程序都很陌生。 我查看了require.js并进行了以下操作。
Background.html:
<!doctype html>
<html>
  <head>
    <title>Tab Manager</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <h1>Tab Manager</h1>
    <script data-main="scripts/score.js" src="scripts/require.js"></script>
  </body>
</html>

background.js:

// gets a dictionary of existing windows ids as keys and tab arrays as values.
function get_windows() 
{
    var window_dict = {};
    chrome.windows.getAll({populate:true}, windowArr =>{
        var i;
        for (i = 0; i < windowArr.length; i++) {
            var window = windowArr[i];
            var window_id = window.id;
            var tabs = window.tabs;
            window_dict[window_id] = tabs;
          }
        console.log(window_dict);
        main(window_dict);
    })
    
}

function starting_scores(window_dict)
{
    var scores = [];
    var i;
    var j = 0;
    var total_tabs = [];
    for (const [window_id, tabs] of Object.entries(window_dict)) {
        for (i = 0; i < tabs.length; i++){
            scores[j] = new Score(tabs[i], window_id);
            j = j++;
        }}
    return scores;
}

function main(window_dict)
{
    var scores = starting_scores(window_dict);
    console.log(scores);
}

get_windows();

score.js:

class Score
{   
    // Constructor
    constructor(tab, window_id)
        {
        this.window_id = window_id; // The window id of the window that contains the tab.
        this.tab = tab; 
        this.url = tab.url;
        this.active = tab.active; // If the tab is currently looked at then it's active.
        this.audible = tab.audible; // If the tab is playing audio then audible will be true.
        this.discarded = tab.discarded; // If the tab is already unloaded but not closed this will be true.

        /* If the new tab is active then the timer is set to zero because 
        the user hasn't spent any time not using the tab. Otherwise a timer starts. */
        if(this.active == true){
            this.timer == 0;}
        else{
            this.timer = performance.now;}
        }
    
    // Get methods
    getWindowId() {
        return this.window_id;
    }
    getTab() {
        return this.tab;
    }
    getUrl() {
        return this.url;
    }
    getActive() {
        return this.active;
    }
    getAudible() {
        return this.audible;
    }
    getDiscarded() {
        return this.discarded;
    }
    getTimer() {
        return this.timer;
    }

    // Set methods
    setWindowId(window_id) {
        this.window_id = window_id;
    }
    setTab(tab) {
        this.tab = tab;
    }
    setUrl(url) {
        this.url = url;
    }
    setActive(active) {
        this.active = active;
    }
    setAudible(audible) {
        this.audible = audible;
    }
    setDiscarded(discarded) {
        this.discarded = discarded;
    }
    setTimer(timer) {
        this.timer = timer;
    }
}

我正在尝试构建一个扩展程序,为每个标签页创建使用得分并删除低得分的选项卡。不用担心逻辑,我只是无法让score.js在background.js中工作。

非常感谢任何帮助。

2个回答

20

更新@wOxxOm的答案,从Manifest v3开始,您不能使用background.page,但您可以直接将脚本作为模块加载。

manifest.json

"background": {
    "service_worker": "background.js",
    "type": "module"
}

background.js

import Score from './score.js';

score.js

export default class Score

1
现在它显示“Service worker注册失败”。 - Sunil Garg
看起来这是因为在安装过程中后台脚本抛出了错误:https://dev59.com/QFEG5IYBdhLWcg3wbtdr#66115801 - Trevin Avery
@TrevinAvery content.js文件怎么样?我可以在里面导入函数吗? - Volatil3
我不知道content.js是什么,但你可以通过模块的方式加载它,可以通过上面提到的背景方式或者通过脚本标签的方式,就像@wOxxOm的回答中所示。如果你这样做了,那么你导出的任何内容都将是可访问的。因此,只需导出你想要的函数即可。 - Trevin Avery
5
如果有人在遇到“Service worker registration failed”一小时左右,解决方法是使用import Score from './score.js';而不是import Score from './score';。就这样。 - nu_popli

6

ManifestV3

清单V3

There are several methods:
https://dev59.com/VlEG5IYBdhLWcg3wac6f#66408379

ManifestV2:

移除require.js并使用内置的ES模块导入。

manifest.json:

清单.json:

"background": {
  "page": "background.html"
}

background.html,整个文件只有一行:

<script src="background.js" type="module"></script>

background.js,插入在文件开头:

import Score from './score.js';
导入的脚本 score.js,更改第一行:
export default class Score

请注意:如果您不使用类似Webpack的打包器/编译器,则import语句中的文件名必须包括路径(./表示“相同目录”)和文件扩展名,否则它将无法正常工作。模块的典型文件扩展名为.mjs


1
非常感谢。我在导入文件方面遇到了很多麻烦,以至于我认为 JavaScript 不适合我。这实际上是我正在做的一个学校项目,而且截止日期就快到了。这帮了我很多,让我能够继续编码。 - CodeSlayer55
(清单 V3)我收到了这个扩展错误:Uncaught SyntaxError: Unexpected token 'export'。 - Alex 75
@Alex75,这个答案是针对ManifestV2的。请参考chrome extension mv3 - Modularize service worker js file - wOxxOm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接