Min*_*ark 12 google-chrome google-chrome-extension chrome-extension-manifest-v3
我正在关注 chrome 官方网站https://developer.chrome.com/docs/extensions/mv3/getstarted/中发布的如何使 chrome 扩展入门
我复制并粘贴了所有代码并以相同的方式运行。但就我而言,当我运行时chrome.scripting.executeScript,它会导致"Uncaught (in promise) Error: Cannot access a chrome:// URL"错误。
我不知道有什么问题。这是我从上面的链接复制的代码。
{
"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"
}
}
Run Code Online (Sandbox Code Playgroud)
let color = '#3aa757';
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({ color });
console.log(`default color: ${color}`);
});
Run Code Online (Sandbox Code Playgroud)
// 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;
});
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css" />
</head>
<body>
<button id="changeColor"></button>
<script src="popup.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
你有好主意吗??
VJP*_*Paz 18
当您尝试触发事件时,请确保您不在chrome://extensions/或类似的情况下。
Ale*_* 75 11
您可以检查 URL 并避免注入“chrome://”脚本:
// skip urls like "chrome://" to avoid extension error
if (tab.url?.startsWith("chrome://")) return undefined;
chrome.scripting.executeScript({
//...
Run Code Online (Sandbox Code Playgroud)
我也在background.js中执行此操作,因为我在那里注入脚本:
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// skip urls like "chrome://" to avoid extension error
if (tab.url?.startsWith("chrome://")) return undefined;
if (tab.active && changeInfo.status === "complete") {
chrome.scripting.executeScript({
//...
Run Code Online (Sandbox Code Playgroud)
笔记。要访问tab.url,您需要清单(V3)“权限”中的“选项卡”。
| 归档时间: |
|
| 查看次数: |
16438 次 |
| 最近记录: |