繁体   English   中英

如何分配键盘快捷键以在 Chrome Extension Manifest v3 中运行 function

[英]How to assign Keyboard Shortcut to run a function in Chrome Extension Manifest v3

我一直在尝试实现Action 命令,以便键盘快捷键将触发 function inside background.js 当按下键盘快捷键时,当前代码不会发生任何事情。

理想情况下,键盘快捷键会触发background.js中的 function 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
  });
});

command api 用于侦听和操作键盘快捷键。

清单文件

{
  "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"
      }
    }
  },
  ...
}

可以在background.js添加一个监听器来监听命令。

背景.js

chrome.commands.onCommand.addListener((command) => {
  console.log(`Command: ${command}`);
});

关于键盘快捷键的完整文档。

lejlun 的回答不正确:正如 Chrome 扩展文档所说:

_execute_action (Manifest V3)、_execute_browser_action (Manifest V2) 和 _execute_page_action (Manifest V2) 命令分别用于触发您的操作、浏览器操作或页面操作。 这些命令不像标准命令那样调度 command.onCommand 事件。

您正确使用了action.onClicked事件。

问题是在executeScript的参数中你写了function而不是func 根据文档,function 调用应如下所示:

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

此外,您尝试变红的页面可能将其背景颜色设置为!important 在这种情况下,您对背景颜色的更改不会有任何效果,因为它会被!important样式覆盖。 要确保应用背景色,您可以使用document.body.style.setProperty('background-color', 'red', 'important');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM