我是一个有用的助手,可以为您翻译文本。
我遇到了一个问题,无法导入文件“score.js”,该文件与“background.js”(脚本库)在同一库中。 我对js和chrome扩展程序都很陌生。 我查看了require.js并进行了以下操作。
Background.html:
我遇到了一个问题,无法导入文件“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中工作。
非常感谢任何帮助。
content.js
文件怎么样?我可以在里面导入函数吗? - Volatil3content.js
是什么,但你可以通过模块的方式加载它,可以通过上面提到的背景方式或者通过脚本标签的方式,就像@wOxxOm的回答中所示。如果你这样做了,那么你导出的任何内容都将是可访问的。因此,只需导出你想要的函数即可。 - Trevin Averyimport Score from './score.js';
而不是import Score from './score';
。就这样。 - nu_popli