skip to Main Content

I tried to intercept all enters in a page and send Shift+enter, it creates an endless loop of shift enters. After adding the logic to skip ‘Shift+Enter’, it sends the ‘Enter’ first, then a ‘Shift+Enter’. I am confused with the result. How to handle this?

document.addEventListener('keydown', function(event) {
    if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        
        const myevent = new KeyboardEvent('keydown', {
            key: 'Enter',
            shiftKey: true,
            bubbles: true
        });
        
        //  alert('Test Enter');
        event.target.dispatchEvent(myevent);
    }
});

Please note: I use ‘User JavaScript and CSS’ to load this js to work on any webpage, especially in chatgpt website.

2

Answers


  1. I would suggest using early returns like this

    document.addEventListener('keydown', function(event) {
      if (event.key !== 'Enter') {
        return
      }
      if (event.shiftKey === true) {
        return
      }
      event.preventDefault();
    
      const myevent = new KeyboardEvent('keydown', {
        key: 'Enter',
        shiftKey: true,
    
        bubbles: true
      });
    
      console.debug('shift+enter')
    
      event.target.dispatchEvent(myevent);
    });
    Login or Signup to reply.
    1. Register document to the "keyup" event.

    2. If the key.code is "Enter" then cancel it with .preventDefault().

    3. Reassign the event object as the new KeyboardEvent with .type "keydown". Add code: "Enter" and shiftKey: true to the options object.

    4. Trigger new KeyboardEvent with .dispatchEvent().

    5. Define a variable that confirms that "shiftKey" was triggered:

      let shift = event.shiftKey ? "Shift" : null;
      
    6. Log the event to confirm:

      console.log(`Event: ${event.type}, Key: ${event.code} + ${shift}`);
      
    document.addEventListener('keyup', function(event) {
    
      if (event.code === 'Enter') {
        event.preventDefault();
      }
      
      event = new KeyboardEvent('keydown', {
        code: 'Enter',
        shiftKey: true,
        bubbles: true
      });
    
      this.dispatchEvent(event);
      
      let shift = event.shiftKey ? "Shift" : null;
      
      console.log(`Event: ${event.type}, Key: ${event.code} + ${shift}`);
    
    });
    <p>Click here then hit the <kbd>Enter</kbd> key.</p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search