Chrome 扩展 - 使用热键点击页面上的元素(按钮)

Chrome Extension - click on element (button) on the page using hotkey

我正在尝试使用热键单击页面上的特定按钮,该热键将触发 javascript 来执行此操作。 但无论我尝试什么,我都会得到“click of undefined

热键工作正常,但唯一的问题是点击没有 ID 的元素(按钮),只有 class

这是我的 manifest.json

    {
    "name": "Clicking plugin",
    "description": "Just a simple pluugin",
    "version": "1.0",
    "manifest_version": 2,
    "background": {
        "scripts": ["script.js"]
    },
    "commands": {
    "endorse_cmd": {
      "suggested_key": {
        "default": "Ctrl+X"
      },
      "description": "nothing"
    },
    "claim_cmd": {
      "suggested_key": {
        "windows": "Ctrl+Y"
        },
        "description": "nothing"
        }
    }
}

这是我的 script.js

var elems = document.getElementsByClassName('VotingButton VotingButton--upvote btn-white');
var votedUp = document.getElementsByClassName('VotingButton VotingButton--upvote btn-white VotingButton--votedUp');
var elems1 = document.getElementsByClassName('task-skip-submit js-next-question');
var elems2 = document.getElementsByClassName('btn-next-task js-next-question');



chrome.commands.onCommand.addListener(function (command) {
    if (command == "endorse_cmd") {
        alert("X Pressed"); //this works
        if (votedUp.length > 0){ elems1[0].click(); } else if (elems.length > 0){ elems[0].click(); elems1[0].click(); } else if (elems2.length > 0){ elems2[0].click();} else if (elems1.length > 0){ elems1[0].click();} //This is not working
        
        }
        else if (command == "claim_cmd") {
            alert("Y Pressed"); //this works
            var claimBtn = document.getElementsByClassName('btn-blue js-claim-question claim-button');//This is not working
            claimBtn[0].click();//This is not working
        }
});

我要单击的按钮如下所示:

<button class="btn-blue js-claim-question claim-button">Claim questions</button>

基本上,您无法从后台脚本访问 activeTab DOM。您需要 运行 executeScript() 使用将获取信息并模拟点击的代码:

后台脚本:

chrome.tabs.executeScript({
  code: `
    var claimBtn = document.getElementsByClassName('btn-blue js-claim-question claim-button');
    claimBtn[0].click();`
});

manifest.json:

{
  /* other things */
  permissions: [
    "activeTab"
  ]
}

将我为后台脚本提供的代码放在Ctrl+Y命令中。