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

Vindictive
  • 311
  • 7
  • 19
  • 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. – Vindictive Sep 13 '17 at 09:46
  • Try adding a `event.stopPropagation();` after your `split();` – m.nachury Sep 13 '17 at 10:50
  • stopPropagation(); didn't work but thanks. – Vindictive Sep 13 '17 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. – bamtheboozle Sep 13 '17 at 10:59
  • I think you might be right, I'm new to extensions I see there are content scripts which is where I have the code placed now. And there are Event pages which based on it's function I don't think that's what I want. Or I don't know how to structure it. If you're knowledgeable about Chrome extensions can you suggest what I should research? – Vindictive Sep 13 '17 at 11:16
  • 1
    use true for [useCapture parameter](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) of addEventListener: document.addEventListener("keydown", handler, true); and declare your content script to "run_at": "document_start", don't forget to reload the extension. – wOxxOm Sep 13 '17 at 12:20
  • @wOxxOm Thanks for the suggestion. I followed your instructions. No luck. Also tried "run_at": "document_end" and that didn't work either. – Vindictive Sep 13 '17 at 21:18

1 Answers1

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.

Vindictive
  • 311
  • 7
  • 19