[英]Chrome Extension - click on element (button) on the page using hotkey
我正在嘗試使用將觸發 javascript 的熱鍵單擊頁面上的特定按鈕。 但無論我嘗試什么,我都會得到“ click of undefined
”
熱鍵工作正常,但唯一的問題是單擊沒有 ID 的元素(按鈕),只有class
這是我的清單。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命令中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.