Search code examples
javascriptbrowsermicrosoft-edgemicrosoft-edge-extension

MS Edge api error "browser is not defined"


I am trying to build an extension for new Microsoft Edge browser. After loading the unpacked extension I am getting this error,

Uncaught ReferenceError: browser is not defined

I have read the microsoft edge docs that all extension APIs are under the browser namespace.

I have included storage permission in my manifest.json file. This my code from manifest.json file,

{
  "manifest_version": 2,
  "name": "Demo",
  "author": "Plaban Kumar Mondal",
  "description": "Demo",
  "version": "1.0.0",
  "icons": {
    "128": "icon128.png",
    "48": "icon48.png",
    "16": "icon16.png"
  },
  "browser_action": {
    "default_icon": {
      "48": "icon48.png",
      "16": "icon16.png"
    },
    "default_popup": "popup.html"
  },
  "options_page": "options/options.html",
  "permissions": ["activeTab", "storage"]
}

this is my javascript file where I am using the browser namespace,

const checkboxes = document.querySelectorAll("input[type='checkbox']");

checkboxes.forEach((checkbox) => {
  return checkbox.addEventListener("change", () => {
    if (checkbox.changed) {
      browser.storage.local.set({ [checkbox.name]: true }, () => {
        browser.storage.onChanged.addListener(() => console.log("true"));
      });
    } else {
      browser.storage.local.set({ [checkbox.name]: false }, () => {
        browser.storage.onChanged.addListener(() => console.log("changed to false"));
      });
    }
  });
});

what is the problem with my code?


Solution

  • Please try with chrome - for chromium-based edge, the browser will support the code below - see https://learn.microsoft.com/en-us/microsoft-edge/extensions-chromium

    const checkboxes = document.querySelectorAll("input[type='checkbox']");
    
    checkboxes.forEach((checkbox) => {
      return checkbox.addEventListener("change", () => {
        if (checkbox.changed) {
          chrome.storage.local.set({ [checkbox.name]: true }, () => {
            chrome.storage.onChanged.addListener(() => console.log("true"));
          });
        } else {
          chrome.storage.local.set({ [checkbox.name]: false }, () => {
            chrome.storage.onChanged.addListener(() => console.log("changed to false"));
          });
        }
      });
    });