在Automator中运行时,为什么只能访问window.properties()?

时间:2019-05-09 05:31:20

标签: javascript macos jxa

我正在尝试编写一个JXA脚本,该脚本会垂直扩展当前应用程序的当前窗口的边界,使其从屏幕的顶部到底部。如果我以“运行JavaScript”快速操作在Automator中运行以下脚本,则该脚本可以正常工作:

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
};

我希望将此脚本绑定到热键。当我在“系统偏好设置”->“键盘”->“快捷方式”->“服务”->“常规”中绑定并尝试在某些应用程序处于活动状态(例如iTerm 2)时将其激活时,它不起作用,并且出现错误:

The action “Run JavaScript” encountered an error: “Error on line 4: TypeError: undefined is not an object (evaluating 'window.properties')”

请注意,如果我将脚本修改为始终可在特定应用(var app = Application("Google Chrome");)上运行并在Automator中运行,则它将起作用。

1 个答案:

答案 0 :(得分:0)

您需要获取当前使用的应用程序(最前面的应用程序),因为当前应用程序是运行Javascript代码的应用程序。这就是为什么当代码在Automator中运行以及对某个应用程序进行硬编码时,该代码才能起作用的原因。

要使用该应用程序,可以使用以下两行:

	var frontAppName = Application("System Events").processes.whose({frontmost: {'=': true }})[0].name();
	var frontApp = Application(frontAppName);

我无法确定该错误,但我了解通常认为包括标准定义是一种好习惯,并且已将其包含在下面的修订代码中,使用热标记时不会导致此错误组合键。

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
	};
}