KeyboardJS
KeyboardJS copied to clipboard
Error when starting the program
C:\Users\fahru\OneDrive\Desktop\Project\non-fullsize-keyboard-keymapping\node_modules\keyboardJS\dist\keyboard.js:614 throw new Error('Cannot find window functions addEventListener or attachEvent.');
It's showing this error when running it, even with the simplest code :
`const keyboardJS = require('keyboardJS');
keyboardJS.on("n", function () {alert("n pressed");}); `
` const keyboardJS = require('keyboardJS');
keyboardJS.bind('a', (e) => { // pressKey keyboardJS.pressKey('b');
// releaseKey
keyboardJS.releaseKey('b');
});`
I am encountering this same error when attempting to import keyboardjs into some test code.
Here is a snippet to demonstrate what I mean:
import { JSDOM } from 'jsdom'
import assert from 'assert'
import keyboardjs from 'keyboardjs'
// create mocked window object
const window = new JSDOM().window
const document = window.document
// pass this to keyboardjs?
keyboardjs.watch(document)
It seems like keyboardjs attempts to access the window object as it's loaded, and I am not sure how to prevent it from doing that.
I was able to get this to work using dynamic imports.
You can use an import function, which returns a Promise for when the module is imported.
JSDOM can be imported first, and then used to create an embedded window object which we then add to the global scope.
Then, we can import keyboardjs using the same mechanism.
Here is roughly the code I ended up with:
// import JSDOM first
import('jsdom').then(async module => {
const window = new module.JSDOM().window
// now set the global window object to the JSDOM window
globalThis.window = window
// _now_ import keyboardjs
const keyboardjs = await import('keyboardjs')
const document = window.document
return { keyboardjs, document }
}).then(({ keyboardjs, document }) => {
// test code goes here, and can use keyboardjs and document
})
Just a quick update there, I've updated the lib to support non browser environments removing the need to perform a work around. See commit https://github.com/RobertWHurst/KeyboardJS/commit/3ab58eb3cdcd78b57da08139babc639c1591850e