【问题标题】:Why can I only access window.properties() when running from within Automator?为什么我只能在 Automator 中运行时访问 window.properties()?
【发布时间】:2019-09-26 21:32:56
【问题描述】:

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

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 中运行它,它可以工作。

【问题讨论】:

    标签: javascript macos javascript-automation


    【解决方案1】:

    您需要获取当前正在使用的应用程序(最前面的应用程序),因为当前应用程序是运行 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
    	};
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      • 2011-08-02
      • 2014-11-09
      • 1970-01-01
      • 2017-02-23
      • 2023-03-19
      • 2023-01-24
      相关资源
      最近更新 更多