如何在 Chrome Extension Manifest v3 Manifest.json背景.js

问题描述

我一直在尝试实现 Action command,以便键盘快捷键触发 background.js 中的函数。当前代码在按下键盘快捷键时不会发生任何事情。

理想情况下,键盘快捷键会触发 background.js 中的 reddenPage 函数

我假设一些代码需要放在 background.js 中,我只是不确定代码应该放在什么位置或内容。非常感谢任何帮助!

Manifest.json

{
  "name": "Page Redder","action": {},"manifest_version": 3,"version": "0.1","description": "Turns the page red when you click the icon","permissions": [
    "activeTab","scripting"
  ],"background": {
    "service_worker": "background.js"
  },"commands": {
    "_execute_action": {
      "suggested_key": {
        "default": "Ctrl+Shift+F","mac": "MacCtrl+Shift+F"
      }
    }
  }
}

background.js

function reddenPage() {
  document.body.style.backgroundColor = 'red';
}

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: { tabId: tab.id },function: reddenPage
  });
});

解决方法

Echo [main code] api 用于监听键盘快捷键并对其进行操作。

Manifest.json

Pause

可以向 command 添加侦听器以侦听命令。

背景.js

{
  "name": "My extension",...
  "commands": {
    "run-foo": {
      "suggested_key": {
        "default": "Ctrl+Shift+Y","mac": "Command+Shift+Y"
      },"description": "Run \"foo\" on the current page."
    },"_execute_action": {
      "suggested_key": {
        "windows": "Ctrl+Shift+Y","mac": "Command+Shift+Y","chromeos": "Ctrl+Shift+U","linux": "Ctrl+Shift+J"
      }
    }
  },...
}

Full Documentation regarding keyboard shortcuts.

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...