1

I want to be able to simulate keyboard events "Ctrl+Shift+N" using jQuery in Chrome. What I've tried is:

var e = jQuery.Event("keypress");
e.ctrlKey = true;
e.shiftKey = true;
e.keyCode = e.which = 78;
$("body").trigger(e);

That shortcut is supposed to open Chrome Incognito window. But having no luck. What am I doing wrong?

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
quldude
  • 507
  • 5
  • 16

1 Answers1

0

It works, if you run the snippet and see 78 inside the content (78 is the keycode of N).

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
  $(function () {
    $("body").keypress(function (e) {
      $(this).html(e.which);
    });
    var e = jQuery.Event("keypress");
    e.ctrlKey = true;
    e.shiftKey = true;
    e.keyCode = e.which = 78;
    $("body").trigger(e);
  });
</script>

If you want your Chrome browser to open up a new incognito window, you are mistaken. These will not interfere with your browser shortcuts and they run in sandboxed mode. This is like you are trying to issue Ctrl + Alt + Del from your browser, which will be a huge security issue!

There's a good answer here, that might be related:

If your goal is to achieve a browser analog of a sendKeys function (a function where you send keystrokes directly to the keyboard buffer) then you will be unable to achieve this. Triggering key events in a browser sends events to DOM handlers not the keyboard buffer. For this reason simulating an actual working keyboard in the browser which sends strokes to the keyboard buffer is impossible without a security breaching hole from the browser into the OS.

So the simple answer for your intention is No!

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252