Reputation: 921
I am trying to write a JXA script which extends the bounds the current window of the current application vertically so it reaches from the top to the bottom of the screen. If I run the following script in Automator as a "Run JavaScript" quick action, it works:
var app = Application.currentApplication();
var window = app.windows[0];
var orig_bounds = window.properties().bounds;
var vertical_res =
Application("Finder").desktop.window.properties().bounds.height;
window.bounds = {
"x": orig_bounds.x,
"y": 0,
"width": orig_bounds.width,
"height": vertical_res
};
I want this script to be bound to a hotkey. When I bind it in System Preferences -> Keyboard -> Shortcuts -> Services -> General and try to activate it while some app is active (say, iTerm 2), it doesn't work, and I get the error:
The action “Run JavaScript” encountered an error: “Error on line 4: TypeError: undefined is not an object (evaluating 'window.properties')”
Note that if I modify the script to always operate on a specific app (var app = Application("Google Chrome");
) and run it in Automator, it works.
Upvotes: 0
Views: 556
Reputation: 21
You need to get the application currently in use (the front most application), as the current application is the one running the Javascript code. This is why the code works when it's run in Automator and when a certain application is hard-coded.
To get the application in use you can use the two lines below:
var frontAppName = Application("System Events").processes.whose({frontmost: {'=': true }})[0].name();
var frontApp = Application(frontAppName);
I can't be certain about the error but I understand that it is generally considered good practice to include the Standard Definitions, and I've included it in the revised code below which doesn't cause this error when using a hot key combination.
function run(input, parameters) {
var app = Application.currentApplication();
app.includeStandardAdditions = true;
var frontAppName = Application("System Events").processes.whose({frontmost: {'=': true }})[0].name();
var frontApp = Application(frontAppName);
var window = frontApp.windows[0];
var orig_bounds = window.properties().bounds;
var vertical_res = Application("Finder").desktop.window.properties().bounds.height;
var orig_x = orig_bounds.x;
var orig_width = orig_bounds.width;
frontApp.windows[0].bounds = {
x: orig_x,
y: 0,
width: orig_width,
height: vertical_res
};
}
Upvotes: 2