通常,当您编写 .jsx 脚本来自动化 Adobe 产品(如 InDesign、Illustrator 或 Photoshop)时,您可以从 ExtendScript IDE 编写、调试和执行脚本。是否可以绕过 ExtendScript 并从第三方程序运行脚本?
我认为 Adobe 产品有一个内置的 JavaScript 解释器,ExtendScript 可以连接到它来访问 Adobe 对象模型并自动化他们的软件。我希望能够像在 ExtendScript 中一样直接连接到该解释器并运行 jsx 文件。
最佳答案
您使用的是 Mac 吗?如果是这样,您可以将 AppleScript 与 osascript
工具结合使用来执行您的 JavaScript。以下是一些示例:
运行 JSX 并返回一个值
将其另存为 ~/temp/foo.scpt:
tell application "Adobe Illustrator"
-- 'do javascript' runs any arbitrary JS.
-- We're using the #include feature to run another
-- file. (That's an Adobe extension to JS.)
--
-- You have to pass a full, absolute path to #include.
--
-- The documentation alleges that 'do javascript'
-- can be passed an AppleScript file object, but
-- I wasn't able to get that to work.
do javascript "#include ~/temp/foo.jsx"
end tell
并将其保存为 ~/temp/foo.jsx:
var doc = app.activeDocument;
var numLayers = doc.layers.length;
// The last value in the JSX file will be printed out by
// osascript.
numLayers;
现在,从命令行运行 osascript ~/temp/foo.scpt
它将打印事件 Illustrator 文档中的层数。
从 JavaScript 中获取数据是有限制的。您不能从 JavaScript 中打印到标准输出。相反,将您要返回的值作为 JSX 文件的最后一条语句;它将由 osascript
打印。 (原因如下:JSX 文件中的最后一个值是 do javascript
AppleScript 语句的返回值。这也是 AppleScript 文件中的最后一个值,osascript
打印最终值。)
您从 JavaScript 返回的值可以是数字、字符串、数组或在转换为字符串时保留其值的任何其他内容。如果您想返回一个复杂的对象,您需要#include 一个 JSON 库并对该对象调用 .toJSONString()
。
向 JSX 传递参数
要将参数传递给 JSX 代码,请遵循以下示例:
文件 ~/temp/args.scpt:
on run argv
tell application "Adobe Illustrator"
set js to "#include '~/temp/args.jsx';" & return
set js to js & "main(arguments);" & return
do javascript js with arguments argv
end tell
end run
文件 ~/temp/args.jsx
function main(argv) {
var layer = app.activeDocument.activeLayer;
app.defaultStroked = true;
app.defaultFilled = true;
// Top, left, width, height (in points).
// Note that parameters start at argv[0].
layer.pathItems.rectangle(argv[0], argv[1], argv[2], argv[3]);
}
然后运行osascript args.scpt 50 30 10 80
调试
do javascript
命令也有启动 ExtendScript 调试器的选项。有关详细信息,请在 AppleScript 编辑器中打开 Illustrator 词典。
关于javascript - 是否可以从 ExtendScript 外部执行 JSX 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3846626/