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
I would suggest using early returns like this
Register
document
to the"keyup"
event.If the
key.code
is"Enter"
then cancel it with.preventDefault()
.Reassign the
event
object as the newKeyboardEvent
with.type
"keydown"
. Addcode: "Enter"
andshiftKey: true
to theoptions
object.Trigger new
KeyboardEvent
with.dispatchEvent()
.Define a variable that confirms that
"shiftKey"
was triggered:Log the event to confirm: