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?

1
  • Look at my answer. I guessed it. Commented Feb 5, 2019 at 16:12

1 Answer 1

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!

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

1 Comment

Thanks for clarifying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.