英文:
Chrome extension that auto press keyboard
问题
I'm trying to create an extension that auto click, it works at Inspect views but seem not work on other page like Keyboard counter
Here are my files:
manifest.json
{
"name": "自动按空格键",
"description": "每隔3秒自动按下空格键",
"version": "1.0",
"manifest_version": 3,
"icons": {
"128": "icon.png"
},
"background": {
"service_worker": "background.js"
},
"permissions": ["activeTab", "scripting"],
"action": {
"default_icon": { "16": "icon.png", "32": "icon.png", "48": "icon.png" },
"default_title": "自动按空格键",
"default_popup": "",
"on_click": { "action": "toggle" }
}
}
background.js
let isActive = false;
let intervalId;
chrome.action.onClicked.addListener(tab => {
isActive = !isActive;
const icon = isActive ? "icon-active.png" : "icon.png";
chrome.action.setIcon({ path: icon });
if (isActive) {
intervalId = setInterval(() => {
console.log("按键已按下");
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => {
document.body.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 32 }));
}
});
}, 3000);
} else {
clearInterval(intervalId);
}
});
It should add to the count on Keyboard counter but it not, and the console log still running at the Inspect view.
英文:
I'm trying to create an extension that auto click, it works at Inspect views but seem not work on other page like Keyboard counter
Here are my files:
manifest.json
{
"name": "Auto Spacebar Presser",
"description": "Automatically presses spacebar button every 3 seconds",
"version": "1.0",
"manifest_version": 3,
"icons": {
"128": "icon.png"
},
"background": {
"service_worker": "background.js"
},
"permissions": ["activeTab", "scripting"]
,
"action": {
"default_icon": { "16": "icon.png", "32": "icon.png", "48": "icon.png" },
"default_title": "Auto Space Presser",
"default_popup": "",
"on_click": { "action": "toggle" }
}
}
background.js
let isActive = false;
let intervalId;
chrome.action.onClicked.addListener(tab => {
isActive = !isActive;
const icon = isActive ? "icon-active.png" : "icon.png";
chrome.action.setIcon({path: icon});
if (isActive) {
intervalId = setInterval(() => {
console.log("Key pressed");
chrome.scripting.executeScript({
target: {tabId: tab.id},
function: () => {
document.body.dispatchEvent(new KeyboardEvent('keydown', {keyCode: 32}));
}
});
}, 3000);
} else {
clearInterval(intervalId);
}
});
It should add to the count on Keyboard counter but it not, and the console log still running at the Inspect view
答案1
得分: 1
当您调查该网站时,您将看到他们是在 keyup
上更新计数,而不是像您的扩展中使用的 keydown
。
将您的代码更改为该事件,它开始注册
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论