Browse a page with custom shortcut keys - web

I want to browse ragecollection.com site using the j and k keys [similar to 9gag.com or google reader] , the default is left right arrow which is not ideal when using a laptop ..
grease monkey script for firefox preffered.

You can't use greasemonkey/javascript to simulate the pressing of a key, as this would cause security problems. The approach in javascript would be to intercept a key press event and trigger the required action that would normally be triggered by a different key press.
To get you started, the following greasemonkey script intercepts g and h character presses on any page:
// ==UserScript==
// #name keytranslate
// #namespace ongar.org
// #description turns g or h keypress into left or right cursor press
// #include *
// ==/UserScript==
function keycheck(e)
{
if (e.keyCode == 71) // code for g
{
// trigger right-cursor event
}
else if (e.keyCode == 72) // code for h
{
// trigger left-cursor event
}
}
window.addEventListener('keydown', keycheck, true);

Related

Within the GameController API, is continuously polling of navigator.getGamepads() required?

EDITED at end!
Within the GameController API, is continuously polling of navigator.getGamepads() required?
I ask because my single call to this function returns a length = 0.
According to my Mac’s Bluetooth System Preferences my Nimbus+ game pad is connected.
Given that, should I use isetInterval` and wait for a length > 0?
EDIT begins here:
Macintosh with Monterey OS 12.4:
Safari (15.5) reports length = 0
Firefox (102.0b6) reports length = 0
Chrome (102.0.5005.115) reports length = 4,
but each in the array being = null
You first wait for the gamepad to be connected, which typically requires "waking" the gamepad by pressing one of its buttons:
window.addEventListener('gamepadconnected', (event) => {
console.log('✅ 🎮 A gamepad was connected:', event.gamepad);
});
Once the gamepad is connected, you start your game loop:
const pollGamepad = () => {
// Always call `navigator.getGamepads()` inside of
// the game loop, not outside.
const gamepads = navigator.getGamepads();
for (const gamepad of gamepads) {
// Disregard empty slots.
if (!gamepad) {
continue;
}
// Process the gamepad state.
console.log(gamepad);
}
// Call yourself upon the next animation frame.
// (Typically this happens every 60 times per second.)
window.requestAnimationFrame(pollGamepad);
};
// Kick off the initial game loop iteration.
pollGamepad();
You should stop polling when the gamepad gets disconnected, which you'll be informed of via an event:
window.addEventListener('gamepaddisconnected', (event) => {
console.log('❌ 🎮 A gamepad was disconnected:', event.gamepad);
});

UIAlertController is not getting dismissed

In my Xamarin iOS app, I have a static helper method that displays an alert dialog. This dialog box needs to automatically go away after a few seconds if the user has still not pressed OK button. Here is the simplified code snippet:
UIAlertController dlg = UIAlertController.Create(title, text,
UIAlertControllerStyle.Alert);
dlg.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null);
UIApplication.SharedApplication.KeyWindow.RootViewController.
PresentViewController(dlg, true, null);
Later, when the timer expires:
t.Elapsed += (s, e) => {
dlg.DismissViewController(true, null);
};
Although, the method DismissViewController is indeed getting invoked, the dialog does not disappear from the screen.
I even tried calling dlg.Dispose() but this didn't help either.
Can someone please help me understand what is it that I am missing? Regards.
The code in event Elapsed is not on the main Thread .
Invoke it on Main Thread.
t.Elapsed += (s, e) =>
{
InvokeOnMainThread(() => {
dlg.DismissViewController(true, null);
});
};

Haxe check which button is pressed (DOM Event)

I recently started programming in Haxe, because I don't like JavaScript too much. I made an EventHandler and wanted to check which button is pressed at this time. In the documentation I found Event.button, but that doesn't work (I think because of browser compatibility, it compiles to e.button in JavaScript which doesn't work).
How else can I check which button is pressed in my event?
To listen to an event you can do:
static function main(){
Browser.document.getElementById('myButton').onClick = clickHandler;
}
function clickHandler(e : Dynamic){
var target : Element = e.target;
}
This is will get the pressed element.

How to create an interruptible loop in node.js

Disclaimer: I'm a Node.js newbie and the following description may be lengthy...
I'm currently trying to teach myself Node.js for a little project I'm after. The project idea is the following: a RaspberryPI runs a Node.js application which allows me to control the colors of an RGB LED strip. The application should be able to set both a static color and also run color wheels that smoothly change colors.
My idea is now to create several Node.js scripts:
A "controller" that does the client communication, sets static colors or is able to start a color wheel
"client scripts" that each run a color wheel. At most one of them would be "alive", started/stopped by the "controller"
I've been able to create a little script that forks another script and is able to stop that script using child.send as follows:
controller.js
var fork = require('child_process').fork,
test2 = fork(__dirname + '/test2.js');
setTimeout(function() { test2.send({func: 'quit'}); }, 5000);
This forks the test2.js script and after 5 seconds sends a quit message that quits test2.js.
test2.js
function runLoop()
{
console.log("Hello");
setTimeout(runLoop, 1000);
}
process.on('message', function(m) {
if (m.func === 'quit')
{
process.exit(0);
}
});
setTimeout(runLoop, 1000);
This "client script" prints "Hello" every second until the controller sends the quit message.
This works pretty well - after 5 seconds the scripts finish gracefully.
My question is now: If I implement a color wheel, I'll need a possibly endless loop that changes the colors of the LED strip. Would the above (with shorter timer values of course - I need something like 10ms here) be a feasible way of implementing an interruptible loop or is there some neater mechanism I don't know of yet?
If you're using setTimeout, you shouldn't even need to fork a new process. Here's how I would write your example:
var ntrvl = setInterval(function() { console.log('Hello'); }, 1000);
setTimeout(function() { clearInterval(ntrvl); }, 5000);
... very simple. With setTimeout and setInterval, you're using asynchronous functions, so you will not block the event loop. When the timer is up, it runs your code, then waits for the next event. You should be able to control all of your "clients", you'll have bandwidth for far more than you'll actually need, all in the same process in this way, concurrently.
All you need to be wary of is that you're not blocking the script. If you attempt to perform any action synchronously (which means that the script will wait for the action to complete before performing the next command), then you need to make sure it runs quickly. If you have to run processor/time intensive tasks synchronously, that's when you'll need to fork a new process.
You're making the life complicated. Your global architecture is as follows:
external trigger --> listener ----------> code that changes color
(ie. web client) (ie. web server)
With that in mind you don't need to fork any process, you can control the LED strip within a single process. Somewhere in your code you'll have an object similar to this:
//"led" is the module that allows you to change the color of a led (suppose 4 leds)
var led = require ("led-controller");
var ColorChanger = module.exports = function (){
this._intervalId = null;
};
ColorChanger.prototype.setColor = function (hex){
//Color in hexadecimal
//Cancel any current interval
cancelInterval (this._intervalId);
led.color (0, hex);
led.color (1, hex);
led.color (2, hex);
led.color (3, hex);
};
ColorChanger.prototype.wheel = function (hex, ms){
//Color in hexadecimal
//"ms" is the time interval between leds going on and off
//Cancel any current interval
cancelInterval (this._intervalId);
//Shutdown all the leds
led.off (0);
led.off (1);
led.off (2);
led.off (3);
//Activate the first led
led.color (0, hex);
//Current active led
var curr = 0;
this._intervalId = setInterval (function (){
//Each "ms" the current led will go off and the next will go on
led.off (curr);
//Next led to activate
curr = ++curr%4;
led.color (curr, hex);
}, ms);
};
Then the listener module uses the ColorChanger.
var ColorChanger = require ("./color-changer");
var changer = new ColorChanger ();
//Set all the leds to red
changer.setColor ("#FF0000");
//Each 10ms one led goes green and the previous is turned off, in an endless loop
changer.wheel ("#00FF00", 10);

RegisterEventHotKey CMD+TAB in Mountain Lion

According to this post:
ShortcutRecorder record CMD+Tab
calling setCanCaptureGlobalHotKeys:YES on the ShortCutRecorder control should allow you to capture CMD+TAB. However, it doesn't seem to work. I created this small app myself to see whats going on:
OSStatus myHotKeyHandler(EventHandlerCallRef nextHandler, EventRef anEvent, void *userData)
{
NSLog(#"YEAY WE DID A GLOBAL HOTKEY");
return noErr;
}
#implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
EventHotKeyRef myHotKeyRef;
EventHotKeyID myHotKeyID;
EventTypeSpec eventType;
eventType.eventClass = kEventClassKeyboard;
eventType.eventKind = kEventHotKeyPressed;
myHotKeyID.signature = 'mhk1';
myHotKeyID.id = 1;
InstallApplicationEventHandler(&myHotKeyHandler, 1, &eventType, NULL, NULL);
OSStatus status = RegisterEventHotKey(kVK_Tab,
cmdKey,
myHotKeyID,
GetApplicationEventTarget(),
0,
&myHotKeyRef);
NSLog(#"status:%d", status);
}
#end
If I use cmdKey + optionKey, then it does work.
Is there another way to capture CMD+TAB in my own application on Mountain Lion? CMD+OPTION+TAB is not good enough for me.
Things have changed a bit since that question was asked in 2010! ⌘⇥ is detected by Dock.app with an Event Tap, and that event no longer makes it back to the application.
You can still hook ⌘⇥, but you need to beat Dock to it with an Event Tap yourself. Here's some example code, courtesy osxbook.com:
// alterkeys.c
// http://osxbook.com
//
// Complile using the following command line:
// gcc -Wall -o alterkeys alterkeys.c -framework ApplicationServices
//
// You need superuser privileges to create the event tap, unless accessibility
// is enabled. To do so, select the "Enable access for assistive devices"
// checkbox in the Universal Access system preference pane.
#include <ApplicationServices/ApplicationServices.h>
// This callback will be invoked every time there is a keystroke.
//
CGEventRef
myCGEventCallback(CGEventTapProxy proxy, CGEventType type,
CGEventRef event, void *refcon)
{
// Paranoid sanity check.
if ((type != kCGEventKeyDown) && (type != kCGEventKeyUp))
return event;
// The incoming keycode.
CGKeyCode keycode = (CGKeyCode)CGEventGetIntegerValueField(
event, kCGKeyboardEventKeycode);
// Swap 'a' (keycode=0) and 'z' (keycode=6).
if (keycode == (CGKeyCode)0)
keycode = (CGKeyCode)6;
else if (keycode == (CGKeyCode)6)
keycode = (CGKeyCode)0;
// Set the modified keycode field in the event.
CGEventSetIntegerValueField(
event, kCGKeyboardEventKeycode, (int64_t)keycode);
// We must return the event for it to be useful.
return event;
}
int
main(void)
{
CFMachPortRef eventTap;
CGEventMask eventMask;
CFRunLoopSourceRef runLoopSource;
// Create an event tap. We are interested in key presses.
eventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventKeyUp));
eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0,
eventMask, myCGEventCallback, NULL);
if (!eventTap) {
fprintf(stderr, "failed to create event tap\n");
exit(1);
}
// Create a run loop source.
runLoopSource = CFMachPortCreateRunLoopSource(
kCFAllocatorDefault, eventTap, 0);
// Add to the current run loop.
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource,
kCFRunLoopCommonModes);
// Enable the event tap.
CGEventTapEnable(eventTap, true);
// Set it all running.
CFRunLoopRun();
// In a real program, one would have arranged for cleaning up.
exit(0);
}
The downside to this is that you cannot sandbox or ship an application that uses ⌘⇥ on the App Store. Not only should it be obvious why Event Taps are not allowed in those environments (they give you the ability to terminate—and even mutate—events), but the functionality Dock provides on ⌘⇥ is pretty darn useful and can't be remapped to a different keyboard shortcut, so even Witch and Switch avoid it using it by default.

Resources