jquery terminal submit command without pressing enter - javascript

How can i submit a command without pressing the enter button?
I need to make the terminal recognize the speech (that part is already done) and visualize it like a command, than virtually press enter to get an ajax response, is it possible? thanks

push create new interpreter when you have new prompt and new set of commands, to execute the command you can use exec:
term.exec('command');
it will echo the command and execute your command (if you pass true as second argument it will not echo prompt and command being executed), for instancec if you have:
var term = $('...').terminal({
foo: function() {
this.echo('foo');
}
});
term.exec('foo');
will execute your foo function.
or you can simulate keydown event for enter:
var e = $.Event("keydown");
e.ctrlKey = ctrl;
e.altKey = alt;
e.shiftKey = shift;
e.which = e.keyCode = 13;
$(document.documentElement || window).trigger(e);
if you're adding text using term.insert('word'); it will be better to use key down event.
EDIT: key down event may not work with a recent version of jQuery Terminal to trigger the event with jQuery events look at Jest tests.

Related

Triggering keyboard event with JS which pynput recognizes

I am running a website in Python's Bottle framework and I am using the keyboard listener from pynput package. The listener is stopped when delete key is pressed. I want the listener to stop, when a certain button in HTML file is clicked on as well. I want to write a function in JavaScript which will be executed when the button is clicked on and which will trigger the delete key to be pressed (which will consequently make the listener stop).
I have found many JS functions on the internet which trigger the delete button to be pressed, but in none of those examples did the keyboard listener stop. The listener in Python never recognized those events. Does anyone know a way to write such JS function that will trigger a key to be pressed and that the listener in Python will recognize that the key has been pressed?
EDIT:
Here is a part of my code (the pynput part):
def on_press(key):
try:
k = key.char
except:
k = key.name
print('Key pressed: ' + k)
if k in ['left', 'right', 'up', 'down', 'delete']:
#print('Key pressed: ' + k)
return False
def dobi_smer():
listener = keyboard.Listener(on_press = on_press)
listener.start()
listener.join()
with keyboard.Events() as events:
for event in events:
if event.key == keyboard.Key.left:
return 'L'
elif event.key == keyboard.Key.right:
return 'R'
elif event.key == keyboard.Key.up:
return 'U'
elif event.key == keyboard.Key.down:
return 'D'
elif event.key == keyboard.Key.delete:
return 'X'
It listens to the keyboard until one of the arrows or delete key is pressed.
According to the answer, I have created also created a new page in my website which would simulate the delete key being pressed. Here is the code in Bottle:
#bottle.post("/igraj/prekini/")
def igraj_prekini():
print("bla")
keyboard.press(keyboard.Key.delete)
keyboard.release(keyboard.Key.delete)
I have tried to send this post request with AJAX with the following functions:
function prekini() {$.post("/igraj/prekini/")}
and
function prekini() {$.ajax('/igraj/prekini/', {type: 'POST'})}
but neither of these two functions worked as the page /igraj/prekini/ was never reached. (string "bla" was never printed)
You can create a stop button in html, and a write javascript function to listen click in that button. Now, your function works when you clicked that button. So, in that function you can write AJAX code to call some url like /stop_pynput and a /stop_pynput route in bottle like your home page /. And write code that stops pynput there or call some functions there and return something. So, Now you have to gain skill to solve this problem with my idea, if you already know it then that's best but if you aren't familiar with ajax then try asking it in comment.
Steps to do in list form:
Stop button in HTML
Listen click using js
Ajax request to some internal url
In bottle make that route
Now, main part. Inside that route/function or inside that route write run script to stop your pynput
If any queries, then feel free to ask in comment.

Making a javascript chat bot turn chat commands into key presses in another program

Got another chat bot process I am trying to learn. Okay, so I now have a javascript chat bot that connects to a websocket chat room and functions normally. I have gotten it to respond to commands
ex
if (text === "!ping" && (user === "user" || isStaff || isOwner || isSub)) {
channel.sendMessage("pong");
}
What I am trying to do now is take a command such as "!up" and translate that into the bot pressing the "up" arrow on the keyboard inside of another program.
I am not sure of how to get started in this. Every time I try to google it, all I get is how to read keyboard events when someone enters a key into a text box. I am new to javascript so I am unaware of there being an exact name for what it is that I am trying to do. If someone could at least point me into the right direction as to what it is I need to look up in order to learn to do it, I would be very grateful :)
You can use jQuery to simulate these events
Let's say that you want to press up key within <p id="someid"></p> tag of a program.
the codes are:
37 left
38 up
39 right
40 down
You can find codes for other keys through a simple google search
Now if you want to press 'up' arrow, then:
if (text === "!up" && (user === "user" || isStaff || isOwner || isSub)) {
//this function will trigger keyup event
$(function() {
var e = $.Event('keypress');
e.which = 38; // 38 is code for up arrow.
$('#someid').trigger(e);
//you can provide id or class of element where you want this event
//to be triggered
});
}
see also:
Trigger Keypress with
jQuery
Definitive way to trigger keypress events with
jQuery
fiddle - press 'M' key on click of a
button

How to have function trigger from a keypress in node?

I have a script written in javascript which does something to a drone that I have. As of now I run that script in my shell like this node foo.js and the script runs till I abort it using control C. But now I want to be able to run that script and have it listen for keyboard events that I give it (such as ENTER, up/down arrow key, spacebar), and depending on the event it performs a specific function. And when I am done I should be still able to press control C to stop the program. It would be awesome if someone could help me. I am still in highschool and very new to programming.
Here is the script for reference:
var arDrone = require('ar-drone');
var client = arDrone.createClient();
client.takeoff();
client
.after(10000, function() {
this.stop();
this.land();
});
Each keyboard key has a special key code (i.e. f = 70). You can find that here:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
I would use jQuery to trigger these events, the first is any keystroke:
$(function() {
$('client').keydown();
$('client').keypress();
$('client').keyup();
});
The second is specific keystrokes:
$function() {
var e = $.Event('keypress');
e.which = 39; // right arrow
$('client').trigger(e);
});
So then you would have a function called trigger that checked for specific numbers, and you would move your drone accordingly.

Finding function catching key event in Javascript?

I'm writing a user script for a complex web app. The existing code is catching the 'j' and 'k' keydown events.
I'd like to be able to find this function to see what it's doing. Is there a way to list all the key event handlers in a document? Or maybe a way to set a breakpoint somehow in Chrome Developer Tools for when I press the letter?
Yes, in the developer tools, go to the Scripts tab, select the page, go to Event Listener Breakpoints, Keyboard, keydown.
Though this might not necessarily help you much, e.g. if the script is minified or they use a library. But you can give it a try.
If you can get a piece of your script to run first and if the keys are handled at the document level, you can install this intercept to see what part of the code is setting the keyboard handler:
var oldListener = document.addEventListener;
document.addEventListener = function(type, listener, capture) {
if (type == "keydown" || type == "keyup" || type == "keypress") {
console.log("type=" + type + " listener=" + listener.toString().slice(0, 80));
}
return (oldListener.apply(this, arguments));
}

How does one capture a Mac's command key via JavaScript?

How does one capture a Mac's Cmd key via JavaScript?
EDIT: As of 2019, e.metaKey is supported on all major browsers as per the MDN.
Note that on Windows, although the ⊞ Windows key is considered to be the "meta" key, it is not going to be captured by browsers as such.
This is only for the command key on MacOS/keyboards.
Unlike Shift/Alt/Ctrl, the Cmd (“Apple”) key is not considered a modifier key—instead, you should listen on keydown/keyup and record when a key is pressed and then depressed based on event.keyCode.
Unfortunately, these key codes are browser-dependent:
Firefox: 224
Opera: 17
WebKit browsers (Safari/Chrome): 91 (Left Command) or 93 (Right Command)
You might be interested in reading the article JavaScript Madness: Keyboard Events, from which I learned that knowledge.
You can also look at the event.metaKey attribute on the event if you are working with keydown events. Worked wonderfully for me! You can try it here.
I found that you can detect the command key in the latest version of Safari (7.0: 9537.71) if it is pressed in conjunction with another key. For example, if you want to detect ⌘+x:, you can detect the x key AND check if event.metaKey is set to true. For example:
var key = event.keyCode || event.charCode || 0;
console.log(key, event.metaKey);
When pressing x on it's own, this will output 120, false. When pressing ⌘+x, it will output 120, true
This only seems to work in Safari - not Chrome
Basing on Ilya's data, I wrote a Vanilla JS library for supporting modifier keys on Mac: https://github.com/MichaelZelensky/jsLibraries/blob/master/macKeys.js
Just use it like this, e.g.:
document.onclick = function (event) {
if (event.shiftKey || macKeys.shiftKey) {
//do something interesting
}
}
Tested on Chrome, Safari, Firefox, Opera on Mac. Please check if it works for you.
For people using jQuery, there is an excellent plugin for handling key events:
jQuery hotkeys on GitHub
For capturing ⌘+S and Ctrl+S I'm using this:
$(window).bind('keydown.ctrl_s keydown.meta_s', function(event) {
event.preventDefault();
// Do something here
});
keyCode and which are now deprecated so it's advisable to avoid the answers that use those here.
One way to do this now is using the key property on the event argument that comes with DOM keyup and keypress events. Here's a simple example of how to do it:
document.onkeypress = (event) => {
if (event.key === 'Meta') {
console.log("Mac or Windows key was pressed!");
} else {
console.log("Another key was pressed")
}
}
This will trigger on the cmd key press on Mac (See Meta on the MDN docs). The only thing to note here is it will also trigger on the Windows key press too for the users keyboard/OS that support it.
If you need more granular understanding of which Meta key has been pressed, you can use the code property on event which can be either MetaLeft or MetaRight depending on which physical meta key ( cmd) was pressed.
Here is how I did it in AngularJS
app = angular.module('MM_Graph')
class Keyboard
constructor: ($injector)->
#.$injector = $injector
#.$window = #.$injector.get('$window') # get reference to $window and $rootScope objects
#.$rootScope = #.$injector.get('$rootScope')
on_Key_Down:($event)=>
#.$rootScope.$broadcast 'keydown', $event # broadcast a global keydown event
if $event.code is 'KeyS' and ($event.ctrlKey or $event.metaKey) # detect S key pressed and either OSX Command or Window's Control keys pressed
#.$rootScope.$broadcast '', $event # broadcast keyup_CtrS event
#$event.preventDefault() # this should be used by the event listeners to prevent default browser behaviour
setup_Hooks: ()=>
angular.element(#.$window).bind "keydown", #.on_Key_Down # hook keydown event in window (only called once per app load)
#
app.service 'keyboard', ($injector)=>
return new Keyboard($injector).setup_Hooks()
var element = //the DOM element to listen for the key on.
element.onkeyup = function(e) {
if(e.metaKey) {
//command key was pressed
}
}
if you use Vuejs, just make it by vue-shortkey plugin, everything will be simple
https://www.npmjs.com/package/vue-shortkey
v-shortkey="['meta', 'enter']"·
#shortkey="metaEnterTrigged"

Categories