Create a Quick Action To Center Any Window On a Mac

Learn a little bit of JavaScript by creating an Automator Quick Action to center the current window on your Mac. You can assign this to a keybard shortcut and also alter the script to position the window in other ways.



Here’s the code:

function run(input, parameters) {
	
	var frontAppName = Application("System Events").processes.whose({frontmost: {'=': true }})[0].name();
	var frontApp = Application(frontAppName);
	var topWindow = frontApp.windows[0];

	var windowBounds = topWindow.bounds();
	
	var desktopBounds = Application("Finder").desktop.window().bounds();
	
	windowBounds.x = (desktopBounds.width - windowBounds.width) / 2 + desktopBounds.x;
	windowBounds.y = (desktopBounds.height - windowBounds.height) / 2 + desktopBounds.y;
	
	topWindow.bounds = windowBounds;
}

Comments: 6 Responses to “Create a Quick Action To Center Any Window On a Mac”

    Robert Salter
    2 weeks ago

    Followed your code. Works fine with all Apple Applications, however with all of my 3rd party applications, I get the following error message: The action “Run JavaScript” encountered an error: “Error: TypeError: undefined is not an object (evaluating ‘topWindow.bounds’)” Would you be able to briefly explain the error code? Thank You

    2 weeks ago

    Robert: Sounds like the app you using doesn’t have a regular main window. Most apps do.

    Jim Rietz
    2 weeks ago

    I found your video interesting and started to use in with my MBP and external monitor, which is positioned above and half to the right. I did some digging and it seems that javascript does not have the ability to determine the number of screens (monitors) and only has the over all height and width of both monitors moving the window to an odd location. It appears that AppleScript may be able to do that.

    2 weeks ago

    Jim: Just use my suggestion at the end of the video to handle that.

    Christoph
    1 week ago

    Very cool tutorial, thank you!

    Robert Primmer
    6 days ago

    Gary, one nit: the code included on this page differs from the video, adding “+ desktopBounds.x|y”. This addition doesn’t change operation as (at least on my system) as x & y = 0. This does matter however when you add a second monitor. Jim Rietz: this might be your issue. When I used my iPad as Sidecar (on left of main display) I had to change the code to adjust not just for main display resolution, but adjust for new center point (windowBounds.x = ((3008 – windowBounds.width) / 2) – 213.5;

Leave a New Comment Related to "Create a Quick Action To Center Any Window On a Mac"

:
:
:
0/500 (500 character limit -- please state your comment succinctly and do not try to get around this limit by posting two comments)