Disclaimer
Is this project open source? Yes
Is this project completely free? Yes
Is this project vibe-coded beyond the author’s ability to comprehend how it works? No
Save this as a .js file and point CodeScript ToolKit to it as your “Startup script path.” It listens to the softkeyboard being shown or hidden as well if any key is pressed[1]. If one of those things happen, it’ll check if a physical keyboard is connected. If a physical keyboard was connected and wasn’t connected during the last check, it’ll show the notice “Hello, keyboard!” If a keyboard was disconnected and was connected during the last check, it’ll say “Goodbye, keyboard!”
exports.invoke = async (app) => {
let storedCapacitorPhysicalKeyboard = {hasPhysicalKeyboard: null};
async function testPhysicalKeyboard() {
let testCapacitorPhysicalKeyboard = await window.Capacitor?.nativePromise('Keyboard', 'hasPhysicalKeyboard');
if (testCapacitorPhysicalKeyboard.hasPhysicalKeyboard == storedCapacitorPhysicalKeyboard.hasPhysicalKeyboard) return;
storedCapacitorPhysicalKeyboard = testCapacitorPhysicalKeyboard;
if (testCapacitorPhysicalKeyboard.hasPhysicalKeyboard) {
new Notice("Hello, keyboard!");
} else {
new Notice("Goodbye, keyboard!");
}
}
const onKeyDown = () => {
testPhysicalKeyboard();
window.removeEventListener('keydown', onKeyDown);
}
if (app.isMobile) {
testPhysicalKeyboard();
window.addEventListener('keyboardDidShow', async () => {
testPhysicalKeyboard();
window.removeEventListener('keydown', onKeyDown);
});
window.addEventListener('keyboardDidHide', async () => {
testPhysicalKeyboard();
window.removeEventListener('keydown', onKeyDown);
window.addEventListener('keydown', onKeyDown);
});
window.addEventListener('keydown', onKeyDown);
}
}
Why? To do something like this:
On ipad, is there a way to execute a command when external keyboard is de/activated - Help - Obsidian Forum
Though, it’s not instant if the softkeyboard was not visible while connecting or disconnecting the physical keyboard. You either have to press a key on the physical keyboard to tell it you’re using the physical keyboard or open up the softkeyboard[2] to tell it you’re using the softkeyboard.
Running whatever command you want
To get the command IDs for every command palette command, run
console.log(Object.keys(app.commands.commands))
then, in your script, you can use it like
app.commands.executeCommandById('workspace:edit-file-title')[3]. Just replace new Notice("Hello, keyboard!") and/or new Notice("Goodbye, keyboard!").
Only if the softkeyboard is hidden. Also, it stops listening for keys after it “hears” one. It’ll start listening again if the softkeyboard is shown and hidden again. ↩︎
If you’re focused on a text field when disconnecting the physical keyboard, Obsidian should automatically open the softkeyboard, anyway. ↩︎
This goes into editing the current file’s title. ↩︎