Learn how to enhance your workflows by working with windows
getActiveWindow
allows you to get a Window
reference of the system's focused window at the moment of the function call.
getActiveWindow
will return as a Promise
.
1const { getActiveWindow } = require('@nut-tree/nut-js'); 2 3(async () => { 4 const windowRef = await getActiveWindow(); 5})();
Now logging this alone wouldn't be very useful, remember that it's simply a reference:
1// source: 2// ... 3 const windowRef = await getActiveWindow(); 4 console.log(windowRef); 5// ... 6 7// output: 8Window { 9 providerRegistry: DefaultProviderRegistry { 10 // ... 11 }, 12 windowHandle: 2165090 13}
Instead, we want to take advantage of our window's title
and region
properties. Be careful though, these are getter
properties that each return a Promise
instead of a plain value - so we must use await
again:
1const { getActiveWindow } = require('@nut-tree/nut-js'); 2 3(async () => { 4 const windowRef = await getActiveWindow(); 5 const title = await windowRef.title 6 const region = await windowRef.region 7 console.log(title, region) 8})();
You can also await
these values in parallel instead of sequentially, as shown below:
1const { getActiveWindow } = require('@nut-tree/nut-js'); 2 3(async () => { 4 const windowRef = await getActiveWindow(); 5 const [title, region] = await Promise.all([windowRef.title, windowRef.region]) 6 console.log(title, region) 7})();
Additionally, please note that this script will always detail the window information of the shell you run it from. To play around with getting the details of a different window, consider adding a delay before calling getActiveWindow
. We can use nut.js
' own sleep
helper function to achieve this:
1const { getActiveWindow, sleep } = require('@nut-tree/nut-js'); 2 3(async () => { 4 await sleep(4000) // delay for 4 seconds before continuing 5 const windowRef = await getActiveWindow(); 6 const [title, region] = await Promise.all([windowRef.title, windowRef.region]) 7 console.log(title, region) 8})();
1const { getActiveWindow, centerOf, randomPointIn, mouse, sleep } = require('@nut-tree/nut-js'); 2 3(async () => { 4 const windowRef = await getActiveWindow(); 5 const region = await windowRef.region 6 await mouse.setPosition(await centerOf(region)) 7 await mouse.leftClick() 8 await sleep(1000) 9 await mouse.setPosition(await randomPointIn(region)) 10 await mouse.leftClick() 11})();
1const { getActiveWindow } = require('@nut-tree/nut-js'); 2 3(async () => { 4 setInterval(async () => { 5 const windowRef = await getActiveWindow() 6 const [title, region] = await Promise.all([windowRef.title, windowRef.region]) 7 console.log(title, region.toString()) 8 }, 2000) 9})();
© 2023