Search code examples
javascriptjsongoogle-chrome-extension

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": "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


Solution

  • If you check the listeners in your console enter image description here

    When you investigate that site, you will see that they are updating the count on keyup, rather than keydown like you are using in your extension.

    Changing your code to that event it starts registering