问题描述
我正在开发一个 chrome 扩展,我在加载时将 JavaScript 脚本注入到活动选项卡中.我在下面附上了脚本的代码.当我使用 var 声明 myOptions 和 myGlobals 对象时,脚本运行没有任何错误.但是如果我使用 let 来声明它们,那么我会在第一行出现语法错误,指出 myOptions 已经被声明.我什至没有在代码中的任何地方重新声明 myOptions 和 myGlobals 对象.但我试图改变它们的属性值.我无法弄清楚我哪里出错了.我想知道为什么 let 在我的代码中不起作用?
I am developing a chrome extension where I am injecting a JavaScript script into the active tab when it loads. The code of the script I have attached below. When I use var for declaring myOptions and myGlobals objects, the script runs without any errors. But if I use let for declaring them, then I get syntax error on the first line stating that myOptions has already been declared. I have not even redeclared myOptions and myGlobals objects anywhere in my code. But I have tried to change the values of their properties. I am unable to figure out where I am going wrong. I want to know why let does not work in my code?
var myOptions = {
takeNotes:false,
displayNotes:false
}
var myGlobals = {
displayingForm:false,
tabUrl:window.location.href,
notesCache:[]
}
onloadForeground();
function onloadForeground(){
chrome.storage.sync.get(myGlobals.tabUrl, (data)=>{
myGlobals.notesCache = data[myGlobals.tabUrl]?data[myGlobals.tabUrl].savedNotes:[];
console.log(data);
myGlobals.notesCache.forEach(addSticker);
});
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log(request);
if (request.message === "change_takeNotes_option") {
console.log(`Changing take notes option to ${request.value}`);
myOptions.takeNotes = request.value;
sendResponse({
message:"success"
});
return true;
} else if (request.message === "change_displayNotes_option") {
console.log(`Changing display notes option to ${request.value}`);
myOptions.displayNotes = request.value;
displayNotes();
sendResponse({
message:"success"
});
return true;
} else if (request.message === "save_notes_cache") {
console.log("Saved notes");
saveNotes();
sendResponse({
message:"success"
});
return true;
} else if (request.message === "reset_notes") {
console.log("Reset notes");
resetNotes();
sendResponse({
message:"success"
});
return true;
}
});
function displayNotes(){
const notes = document.getElementsByClassName("note");
console.log(notes.length);
for (let i = 0; i < notes.length; i++) {
notes[i].style.visibility = (myOptions.displayNotes)?"visible":"hidden";
}
}
function saveNotes() {
if (myGlobals.notesCache.length > 0) {
chrome.storage.sync.set({[myGlobals.tabUrl]: {savedNotes:myGlobals.notesCache}});
} else {
chrome.storage.sync.remove(myGlobals.tabUrl);
}
}
function displayForm() {
myGlobals.displayingForm = true;
}
function discardForm() {
setTimeout(() => {
myGlobals.displayingForm = false;
}, 500);
}
function addNote(){
console.log("Adding note");
let noteTitle = document.getElementById("note-inputTitle").value;
let noteDescription = document.getElementById("note-inputDescription").value;
if (noteTitle == null || noteTitle.trim() === "") {
alert("The note requires a title");
} else if (noteDescription == null || noteDescription.trim() === "") {
alert("The note requires a description");
} else {
let note = {
title: noteTitle,
description: noteDescription,
}
myGlobals.notesCache.push(note);
console.log("Current note cache");
console.log(myGlobals.notesCache);
discardForm();
}
}
function discardNote(index) {
myGlobals.displayingForm=true;
setTimeout(()=>{
myGlobals.displayingForm=false;
}, 300);
console.log("Discarding note " + index);
myGlobals.notesCache.splice(index, 1);
console.log("Current note cache");
console.log(myGlobals.notesCache);
}
function resetNotes(){
myGlobals.notesCache = [];
console.log(notesCache);
}
这是我用来注入上述脚本的后台脚本
This is the background script I am using to inject the above script
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
console.log(changeInfo);
if (changeInfo.status === "complete" && /^http/.test(tab.url)) {
chrome.scripting.insertCSS({
target: {
tabId: tabId
},
files: ["./foreground.css"]
})
chrome.scripting.executeScript({
target: {
tabId: tabId
},
files: ["./foreground.js"]
})
.then(() => {
console.log("Injected foreground script " + tabId);
chrome.storage.sync.set({ [tabId]: { options:{takeNotes:false, displayNotes:false} } });
})
.catch(err => {
console.log(err);
});
}
});
推荐答案
您在同一页面上使用 executeScript
两次,因此当注入的脚本再次运行时,它会尝试声明一个 let
变量在同一上下文中,但 JavaScript 规范禁止这样做.
You use executeScript
twice on the same page so when the injected script runs again it tries to declare a let
variable in the same context, but this is forbidden by the JavaScript specification.
解决方案:
继续使用
var
将代码包装在 IIFE 中:
Wrap the code in an IIFE:
(() => {
// your entire code here
})()
不要通过在 executeScript 之前添加条件来重新注入脚本两次,例如你可以ping"标签:
Don't reinject the script twice by adding a condition before executeScript e.g. you can "ping" the tab:
// injected file
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg === 'ping') sendResponse(true);
});
// background or popup script
function inject(tabId) {
chrome.tabs.sendMessage(tabId, 'ping', {frameId: 0}, () => {
if (chrome.runtime.lastError) {
// ManifestV2:
chrome.tabs.executeScript(tabId, {file: 'content.js'});
// ManifestV3:
// chrome.scripting.executeScript({target: {tabId}, file: 'content.js'});
}
});
}
这篇关于未捕获的语法错误:标识符“myOptions"已在 JavaScript 中声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!