【发布时间】:2015-12-23 20:42:44
【问题描述】:
我会在 AppleScript 中编写
property foo: "value"
并且该值将在运行之间保存。如何在 Javascript for Automation 中执行此操作?
【问题讨论】:
标签: osascript javascript-automation
我会在 AppleScript 中编写
property foo: "value"
并且该值将在运行之间保存。如何在 Javascript for Automation 中执行此操作?
【问题讨论】:
标签: osascript javascript-automation
用于自动化的 JavaScript 没有直接并行用于 AS 的持久属性(和全局值)机制,但它确实有 JSON.stringify() 和 JSON.parse(),它们非常适合简单的序列化和状态检索。
大概是这样的:
(function () {
'use strict';
var a = Application.currentApplication(),
sa = (a.includeStandardAdditions = true, a),
strPath = sa.pathTo('desktop').toString() + '/persist.json';
// INITIALISE WITH RECOVERED VALUE || DEFAULT
var jsonPersist = $.NSString.stringWithContentsOfFile(strPath).js || null,
persistent = jsonPersist && JSON.parse(jsonPersist) || {
name: 'perfume',
value: 'vanilla'
};
/*********************************************************/
// ... MAIN CODE ...
// recovered or default value
sa.displayNotification(persistent.value);
// mutated value
persistent.value = "Five Spice"
/*********************************************************/
// WRAP UP - SERIALISE TO JSON FOR NEXT SESSION
return $.NSString.alloc.initWithUTF8String(
JSON.stringify(persistent)
).writeToFileAtomically(strPath, true);
})();
(这里有一个更完整的例子:https://github.com/dtinth/JXA-Cookbook/wiki/Examples#properties-which-persist-between-script-runs)
或者,对于简单的键值对而不是任意数据结构,请参阅: https://stackoverflow.com/a/31902220/1800086 关于 JXA 对写入和读取 .plist 的支持
【讨论】: