【问题标题】:Chrome Extension cause "Uncaught (in promise) Error: Cannot access a chrome:// URL"Chrome 扩展程序导致“未捕获(承诺)错误:无法访问 chrome:// URL”
【发布时间】:2021-06-07 15:00:11
【问题描述】:

我正在关注chrome官方网站https://developer.chrome.com/docs/extensions/mv3/getstarted/发布的如何制作chrome扩展入门

我复制并粘贴了所有代码并以相同的方式运行。但就我而言,当我运行chrome.scripting.executeScript 时,会导致"Uncaught (in promise) Error: Cannot access a chrome:// URL" 错误。

我不知道是什么问题。这是我从上面的链接复制的代码。

  • manifest.json
{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "scripting"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "/images/get_started16.png",
      "32": "/images/get_started32.png",
      "48": "/images/get_started48.png",
      "128": "/images/get_started128.png"
    }
  },
  "icons": {
    "16": "/images/get_started16.png",
    "32": "/images/get_started32.png",
    "48": "/images/get_started48.png",
    "128": "/images/get_started128.png"
  }
}
  • background.js
let color = '#3aa757';

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.sync.set({ color });
  console.log(`default color: ${color}`);
});
  • popoup.js
// Initialize button with user's preferred color
let changeColor = document.getElementById('changeColor');

chrome.storage.sync.get('color', ({ color }) => {
  changeColor.style.backgroundColor = color;
});

// When the button is clicked, inject setPageBackgroundColor into current page
changeColor.addEventListener('click', async () => {
  console.log('clicked');
  console.log(chrome.tabs);

  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  console.log(tab);

  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: setPageBackgroundColor,
  });
});

// The body of this function will be executed as a content script inside the
// current page
function setPageBackgroundColor() {
  chrome.storage.sync.get('color', ({ color }) => {
    document.body.style.backgroundColor = color;
  });
}
  • popup.html
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="button.css" />
  </head>
  <body>
    <button id="changeColor"></button>
    <script src="popup.js"></script>
  </body>
</html>

你有什么想法吗??

【问题讨论】:

  • Uncaught (in promise) Error: Cannot access a chrome:// URL" 表示您正在尝试在 url 以 chrome:// 开头的页面中注入内容脚本。不允许使用。尝试首先激活一个网页,然后再次推送操作图标。
  • @Robbi AMG,我明白了。我在 chrome://extension 中进行了测试。你说的对。谢谢!

标签: google-chrome google-chrome-extension chrome-extension-manifest-v3


【解决方案1】:

当您尝试触发事件时,请确保您不在 chrome://extensions/ 或类似的地方。

【讨论】:

  • 我在扩展页面中,因此出现了错误。这对我有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
  • 2020-07-23
  • 1970-01-01
  • 2020-08-02
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多