Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to send "Enter" keypress event? #8977

Closed
binux opened this issue Mar 21, 2017 · 6 comments
Closed

How to send "Enter" keypress event? #8977

binux opened this issue Mar 21, 2017 · 6 comments

Comments

@binux
Copy link

binux commented Mar 21, 2017

  • Electron version: v1.6.2
  • Operating system: macOS

Expected behavior

{
  "type": "keypress",
  "isTrusted": true,
  "init": {
    "key": "Enter",
    "code": "Enter",
    "charCode": 13,
    "keyCode": 13,
    "which": 13
  }
}

And no text written in input box.

Actual behavior

{
  "type": "keypress",
  "isTrusted": true,
  "init": {
    "key": "Enter",
    "code": "Enter",
    "charCode": 69,
    "keyCode": 69,
    "which": 69
  }
}

And text "EnteEnte" written in input box

How to reproduce

const {app, BrowserWindow} = require('electron')

app.on('ready', () => {
  let win = new BrowserWindow();
  win.loadURL(`data:text/html,<input><script>
      function eventToJSON(event) {
        const ret = {
          type: event.type,
          isTrusted: event.isTrusted,
          init: {
            key: event.key,
            code: event.code,
            charCode: event.charCode,
            keyCode: event.keyCode,
            which: event.which,
          }
        };
        console.log(ret);
        return ret;
      };
      const input = document.querySelector('input');
      input.focus();
      let event = null;
      input.addEventListener('keypress', e => event = eventToJSON(e));
      </script>`);
  win.webContents.on('did-finish-load', async () => {
    win.webContents.sendInputEvent({ type: 'char', keyCode: 'Enter' });
    await new Promise(r => setTimeout(r, 200));
    win.webContents.executeJavaScript('event', (result) => {
      console.log(result);
    });
  });
});

BTW: I found a workaround by reading the source code: sendInputEvent({type: 'char', keyCode: String.fromCharCode(0x0D)}), but sending a string instead of an Enter keypress with sendInputEvent({ type: 'char', keyCode: 'Enter' }) is not what I expected.

@zcbenz
Copy link
Member

zcbenz commented Jun 14, 2017

The key passed to sendInputEvent must be a single character, the mappings of accelerators are not support in sendInputEvent (I'm not sure whether we should add the support). We probably need to make the document more clear.

Closing since it is expected behavior.

@zcbenz zcbenz closed this as completed Jun 14, 2017
@binux
Copy link
Author

binux commented Jun 15, 2017

@zcbenz The document said:

keyCode String (required) - The character that will be sent as the keyboard event. Should only use the valid key codes in Accelerator.

Accelerator said:

Available key codes
Return (or Enter as alias)

I think it's clear but wrong in document.

And you have already support KeyIdentifier in KeyboardCodeFromStr when getting the keyCode, just because the text attribute is set for keypress event is not convert https://github.com/electron/electron/blob/master/atom/common/native_mate_converters/blink_converter.cc#L192.

@jbmonroe
Copy link

jbmonroe commented Feb 8, 2018

Unfortunately I don't think it's clear at all. What does the structure that gets sent to sendInputEvent for the Enter or Return key look like? I'm trying to build a virtual keyboard for a kiosk and no permutation or combination of values I send produces the desired result. I either get EnteEnte or an exception thrown because some code under the hood doesn't like the event object I send. This definitely doesn't work:

            function sendCtrl(kc)
            {
                const skc = String.fromCharCode(kc);
                const keys = [
                    { key : skc, keyCode : kc, charCode : kc, type : 'down' },
                    { key : skc, keyCode : kc, charCode : kc, type : 'char' },
                    { key : skc, keyCode : kc, charCode : kc, type : 'up' },
                ];
                sendEvents(keys);  // This wraps sendInputEvent
            }

@FibreFoX
Copy link

@jbmonroe I had this issue too, the electron documentation is flawed here!

To workaround this, I had to use RobotJS to simulate some special keys:

// keyData.key is coming from a function call from a different location, which gets passed to a webview in React
let inputEventToPass = {
    type: 'char',
    keyCode: keyData.key
};
if ( keyData.key === 'ENTER') {
    inputEventToPass = {
        type: 'char',
        keyCode: '\u000d',
        // @ts-ignore
        charCode: 13
    };
}
if ( keyData.key === 'BACKSPACE') {
    let robot = require('robotjs');
    robot.keyTap('backspace');
    /*
    // does not work
    inputEventToPass = {
        type: 'char',
        keyCode: 'Backspace'
    };
    */
    return;
}
if ( keyData.key === 'DELETE') {
    let robot = require('robotjs');
    robot.keyTap('delete');
    /*
    // does not work
    inputEventToPass = {
        type: 'char',
        keyCode: 'Delete'
    };
    */
    return;
}

// @ts-ignore
this.webviewRef.current.sendInputEvent(inputEventToPass);

@zcbenz maybe there should be a statement in the documentation, that these special keys are not "sendable", or a hint how to actually send these keys/chars.

@jbmonroe
Copy link

jbmonroe commented Sep 14, 2018

I could probably live without the Enter key but the lack of Page Up and Page Down makes the customer and the users unhappy.

I'll look into RobotJS to see how much fuss would be involved in adding it to the project (we're just about to completion and the interval before we upload the "final" release is very short). For future projects, this could be exactly what I need.

Thanks for pointing this out to me!

@parkerdan
Copy link

parkerdan commented Dec 20, 2019

This issue should be re-opened.

The documentation is NOT clear

Trying to send Enter and Backspace is a nightmare with the current documentation.

According to the docs, sendInputEvent({keyCode: 'Backspace', type: 'char'}) should be valid, but for Backspace to work, the type must be keyDown.
type keyUp is also invalid for this Accelerator

Also, all the examples above reference a charCode field which is not defined in the documentation and therefore should have no effect

If you truly believe the documentation is clear, lets have a 1-1 conversation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants