2

I'm trying to create a chrome extension that modifies the controls of the popular browser game, Agar.io. Quick summary, in the game SPACE performs the split action. I want to perform the same action but by pressing D instead of SPACE. The extension works fine. It detects that D has been pressed and the my split() function is called; I know this because the alert pops up but the actual game action doesn't perform. I've looked around and tried different ways but nothing is working. Below is my JS file.

window.addEventListener('keydown', keydown);

function keydown(event) {
    if (event.keyCode == 68) { //key D
        split();
    }
}

function split() {
    $("body").trigger($.Event("keydown", { keyCode: 32}));
    $("body").trigger($.Event("keyup", { keyCode: 32}));
    alert("Did it work?");
}

Also tried this method with no success:

var space = jQuery.Event("keydown");
space.which = 32;
$("body").trigger(space);

As shown in this question [Definitive way to trigger keypress events with jQuery

]1

7
  • 1
    @Dekel I've tried the method shown in the question you referenced. It didn't work which is why I posted a new question. Commented Sep 13, 2017 at 9:46
  • Try adding a event.stopPropagation(); after your split(); Commented Sep 13, 2017 at 10:50
  • stopPropagation(); didn't work but thanks. Commented Sep 13, 2017 at 10:57
  • 1
    I think you need to look into content scripts. Basically you want to simulate the press of the D key in the context of the page - which is Agar.io, not in the context of your extension. Commented Sep 13, 2017 at 10:59
  • 1
    use true for useCapture parameter of addEventListener: document.addEventListener("keydown", handler, true); and declare your content script to "run_at": "document_start", don't forget to reload the extension. Commented Sep 13, 2017 at 12:20

1 Answer 1

0

I was able to solve the problem. The code itself is correct and functional but the problem lies in the way I set up my chrome extension. Applying the solution found here https://stackoverflow.com/a/9517879/4651794 I was able to get the code to run. Not sure if this question is has any merit staying up as I thought the problem was with the key commands.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.