[英]How to copy image or file to clipboard using JXA?
我在 ScriptEditor 中使用 JavaScript 有困難
AppleScript 像這樣通過路徑復制圖像到剪貼板
set image to POSIX file ("/Users/lll00lll/Library/Documents/temp.jpg")
set the clipboard to image
但是如何將上面的AppleScript編碼翻譯成JavaScript呢?
JavaScript 這樣可以將字符串復制到剪貼板但不能復制圖像或文件
var app = Application('Script Editor');
app.includeStandardAdditions = true;
app.setTheClipboardTo(str);
或使用 Objective-C?但我不知道如何將其編輯為“generalPasteboard.setData”
$.NSPasteboard.generalPasteboard.clearContents;
$.NSPasteboard.generalPasteboard.setStringForType($(str), $.NSPasteboardTypeString);
這使用 JS-ObjC 橋將一個或多個文件放到剪貼板上。 fsCopy
可以傳遞單個文件路徑或文件路徑數組,並在操作完成后返回剪貼板上的項目數(顯然,這應該等於文件路徑數)。
ObjC.import('AppKit');
function fsCopy(fs) {
const pb = $.NSPasteboard.generalPasteboard;
pb.clearContents;
[].concat(fs).forEach(f =>
pb.writeObjects([
ObjC.unwrap($.NSURL
.fileURLWithPath(f))
])
);
return pb.pasteboardItems.count * 1;
}
稍微簡化CJK 的回答:
// makes Cocoa NS* classes available under $
ObjC.import('AppKit'); // same as ObjC.import('Cocoa');
// necessary to get correct result, but I'm not sure why
$.NSPasteboard.generalPasteboard.clearContents;
// create a Cocoa URL for the file system item
const nsUrl = $.NSURL.fileURLWithPath('/Users/lll00lll/Library/Documents/temp.jpg');
// set the pasteboard to the URL
// .js unwraps the NSUrl reference for use in Obj-C
$.NSPasteboard.generalPasteboard.writeObjects([nsUrl.js]);
說明
在原始問題中,AppleScript 片段將文件的剪貼板設置為URL 。 JSX 片段將剪貼板設置為UTF 字符串。 我嘗試使用 JSX Path()
類型,但它會將剪貼板設置為無意義的風格。
該答案手動創建一個 Cocoa URL 並將粘貼板設置為該值。
writeObjects()
方法也將接受NSImage
,因此您可以在 memory 中傳遞圖像(盡管它比傳遞對文件的引用要慢):
const nsImage = $.NSImage.alloc.initByReferencingFile('/Users/lll00lll/Library/Documents/temp.jpg');
$.NSPasteboard.generalPasteboard.writeObjects([nsImage.js]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.