applescriptjavascript-automation

JXA set window bounds weird issue


script1.js:

function run() {
  const chromeApp = Application('Google Chrome');
  const window = chromeApp.windows[0];
  console.log(window.name());
  window.bounds = {
    x: 0,
    y: 0,
    width: 500,
    height: 500,
  };
  chromeApp.activate();
}

Run:

osascript -l JavaScript script1.js

And it works

script2.js:

function run() {
  const systemEvents = Application('System Events');
  const ap = systemEvents.processes().find(ap => ap.name() === 'Google Chrome');
  console.log(ap.name());
  const window = ap.windows[0];
  console.log(window.name());
  window.bounds = {
    x: 0,
    y: 0,
    width: 500,
    height: 500,
  };
}

Run:

osascript -l JavaScript script1.js

It does NOT work:

script2.js: execution error: Error: Error: Can't set that. (-10006)

But I really need to get script2.js work. Because in my real application, I don't know the application name in advance and I need to fetch the process dynamically base on user interaction. Because I don't know application name, I cannot use script1.js.

Any input is appreciate!


Solution

  • function run() {
      const systemEvents = Application('System Events');
      const p = systemEvents.processes().find(ap => ap.frontmost() === true);
      const ap = Application (p.bundleIdentifier());
      const window = ap.windows[0];
      window.bounds = {
        x: 0,
        y: 0,
        width: 500,
        height: 500,
      };
      }