【问题标题】:MS Edge api error "browser is not defined"MS Edge api 错误“未定义浏览器”
【发布时间】:2020-09-10 07:48:33
【问题描述】:

我正在尝试为新的 Microsoft Edge 浏览器构建扩展。加载解压后的扩展我得到这个错误,

Uncaught ReferenceError: browser is not defined

我已经阅读了所有扩展 API 都在 browser 命名空间下的 microsoft edge 文档。

我已在我的manifest.json 文件中包含存储权限。这是我来自manifest.json 文件的代码,

{
  "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"]
}

这是我使用 browser 命名空间的 javascript 文件,

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

我的代码有什么问题?

【问题讨论】:

  • 您是在 Edge v44 及更早版本还是 Edge v79 及更高版本上进行测试?它们是非常不同的浏览器。 (没有 v45-v78。)
  • 我正在 Edge v85 上进行测试。
  • @Plaban,我同意 Abhinav 提出的将 browser 替换为 chrome 的建议可能会帮助您解决问题。让我们知道它是否适合您。
  • @Deepak-MSFT 我试过chrome,它成功了。

标签: javascript browser microsoft-edge microsoft-edge-extension


【解决方案1】:
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"));
      });
    }
  });
});

For chromium-based edge, the browser will support the above code.

【讨论】:

  • 为什么要使用chrome命名空间?
  • 最新版本的 Edge 将支持 Chromium。现在您可以在 ms edge 浏览器中安装 chrome 扩展。我正在使用版本 85.0.564.44(官方版本)(64 位)。最终推荐,请尝试使用“chrome”。 docs.microsoft.com/en-us/microsoft-edge/extensions-chromium
  • @Abhinav - 该信息属于答案,而不仅仅是对其的评论。
  • 明白。感谢你的信息。我是这只股票溢出的新手。
猜你喜欢
  • 2017-06-16
  • 1970-01-01
  • 2020-09-23
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
相关资源
最近更新 更多