在Node.js中设置自定义MIME类型剪贴板的可行方案(Mac平台)
在Mac上设置带自定义MIME类型的剪贴板(Node.js/AppleScript方案)
AppleScript/osascript 方案
Mac原生的剪贴板API(NSPasteboard)支持直接设置自定义MIME类型,这是最可靠的实现方式,你可以通过命令行或脚本文件执行:
命令行直接执行
osascript -e 'set theClipboard to "你的自定义文本内容"' \ -e 'set theType to "dyn.ah62d4rv4gk8zuxnxnq"' \ -e 'set thePasteboard to current application's NSPasteboard's generalPasteboard()' \ -e 'thePasteboard's clearContents()' \ -e 'thePasteboard's setString:theClipboard forType:theType'
这段脚本通过Objective-C桥接调用系统剪贴板服务,先清空剪贴板内容,再将指定文本以目标MIME类型写入。
独立AppleScript脚本文件
如果需要复用,可将代码保存为.scpt文件:
set targetText to "你的自定义文本内容" set targetMIMEType to "dyn.ah62d4rv4gk8zuxnxnq" set thePasteboard to current application's NSPasteboard's generalPasteboard() thePasteboard's clearContents() thePasteboard's setString:targetText forType:targetMIMEType
执行命令:osascript your-script.scpt
Node.js 方案
Node.js本身没有原生API支持自定义MIME类型的剪贴板操作,但可以通过child_process模块调用osascript命令实现,无需额外依赖:
const { exec } = require('child_process'); function setCustomClipboard(text, mimeType) { // 转义特殊字符避免命令行语法错误 const escapedText = text.replace(/["']/g, match => `\\${match}`); const script = ` set theClipboard to "${escapedText}" set theType to "${mimeType}" set thePasteboard to current application's NSPasteboard's generalPasteboard() thePasteboard's clearContents() thePasteboard's setString:theClipboard forType:theType `.replace(/\n/g, ' '); exec(`osascript -e '${script}'`, (error, stderr) => { if (error) { console.error(`执行失败: ${error.message}`); return; } if (stderr) { console.error(`错误输出: ${stderr}`); return; } console.log('剪贴板已更新'); }); } // 使用示例 setCustomClipboard("需要写入的文本内容", "dyn.ah62d4rv4gk8zuxnxnq");
注意:如果文本包含复杂特殊字符(如反斜杠、换行符),需要补充对应的转义逻辑。
内容的提问来源于stack exchange,提问作者MickCrozier
相关产品推荐
相关产品推荐

