没有 HTML 的 Chrome 扩展,点击图标后直接运行 JS(显示带有 DOM 值的警报)

问题描述 投票:0回答:1

我找不到任何现成的解决方案,尤其是新的 Manifest V3

background
service-worker
架构。

我需要创建一个没有 HTML 的简单 Chrome 扩展,以直接运行 JS,以在单击其图标时显示带有某种 DOM 值(例如 DIV 的 ID)的警报框。但我收到这些错误:

manifest.json

{
  "manifest_version": 3,
  "name": "Practice",
  "description": "Practice",
  "version": "1.0",
  "action": {
    "default_icon": "practice.png"
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["practice.js"],
    "run_at": "document_end"
  }]
}

背景.js

chrome.tabs.onUpdated.addListener(function () {
  chrome.tabs.executeScript(null, { file: "practice.js" });
});

practice.js

var elem = document.getElementById("myDiv");
alert(elem ? 'found: ' + elem.id : 'not found');

background.js 中出现错误:

Uncaught ReferenceError: alert is not defined
google-chrome-extension chrome-extension-manifest-v3
1个回答
0
投票
  1. 您显示的代码甚至无法运行,因为ManifestV3中没有chrome.tabs.executeScript,而是chrome.scripting.executeScript,并且语法完全不同。此外,您还需要
    host_permissions
    (用于无人值守/自动注入)或
    activeTab
    权限(点击注入)。
  2. chrome.tabs.onUpdated 是错误的事件,您需要 chrome.action.onClicked,但在这种特定情况下,更好/更简单的替代方案是在 manifest.json 中指定“default_popup”并删除后台脚本。
  3. 不需要
    content_scripts
    声明,因为它会在每次导航时而不是单击时将指定的脚本注入到每个选项卡中的每个页面中。

//清单.json

{
  "manifest_version": 3,
  "name": "Practice",
  "description": "Practice",
  "version": "1.0",
  "action": {
    "default_popup": "popup.html",
    "default_icon": "practice.png"
  },
  "permissions": ["activeTab", "scripting"]
}

popup.html

<p id=msg></p>
<script src=popup.js></script>

popup.js

(async () => {
  const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
  const [{result, err}] = await chrome.scripting.executeScript({
    target: {tabId: tab.id},
    injectImmediately: true,
    func: id => document.getElementById(id)?.id, // result must be JSON-compatible
    args: ['myDiv'],
  }).catch(err => [{err: err.message}]);
  document.getElementById('msg').textContent = result
    ? 'found: ' + result
    : err || 'not found';
})();
© www.soinside.com 2019 - 2024. All rights reserved.