Search code examples
javascriptgoogle-chrome-extensionsyntax-error

Uncaught SyntaxError: Identifier 'myOptions' has already been declared in JavaScript


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);
      });
  }
});


Solution

  • 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.

    Solutions:

    1. Keep using var

    2. Wrap the code in an IIFE:

      (() => {
      // your entire code here
      })()
      
    3. 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'});
          }
        });
      }