Tutorials

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.

const { getActiveWindow } = require('@nut-tree/nut-js');

(async () => {
    const windowRef = await getActiveWindow();
})();

Now logging this alone wouldn't be very useful, remember that it's simply a reference:

// source:
//  ...
    const windowRef = await getActiveWindow();
    console.log(windowRef);
//  ...

// output:
Window {
  providerRegistry: DefaultProviderRegistry {
  // ...
  },
  windowHandle: 2165090
}

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:

const { getActiveWindow } = require('@nut-tree/nut-js');

(async () => {
    const windowRef = await getActiveWindow();
    const title = await windowRef.title
    const region = await windowRef.region
    console.log(title, region)
})();

You can also await these values in parallel instead of sequentially, as shown below:

const { getActiveWindow } = require('@nut-tree/nut-js');

(async () => {
    const windowRef = await getActiveWindow();
    const [title, region] = await Promise.all([windowRef.title, windowRef.region])
    console.log(title, region)
})();

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:

const { getActiveWindow, sleep } = require('@nut-tree/nut-js');

(async () => {
    await sleep(4000) // delay for 4 seconds before continuing
    const windowRef = await getActiveWindow();
    const [title, region] = await Promise.all([windowRef.title, windowRef.region])
    console.log(title, region)
})();

Examples


Clicking in the active window


const { getActiveWindow, centerOf, randomPointIn, mouse, sleep } = require('@nut-tree/nut-js');

(async () => {
    const windowRef = await getActiveWindow();
    const region = await windowRef.region
    await mouse.setPosition(await centerOf(region))
    await mouse.leftClick()
    await sleep(1000)
    await mouse.setPosition(await randomPointIn(region))
    await mouse.leftClick()
})();

Log active window info repeatedly


const { getActiveWindow } = require('@nut-tree/nut-js');

(async () => {
    setInterval(async () => {
        const windowRef = await getActiveWindow()
        const [title, region] = await Promise.all([windowRef.title, windowRef.region])
        console.log(title, region.toString())
    }, 2000)
})();
Previous
On Screen Search