1
0

More than 3 years have passed since last update.

JXA で、クリップボードから文字列を取得する

Last updated at Posted at 2021-08-28

はじめに

 意外と検索に苦労したのと、状況によっては取得できなかったのでメモしておきます。

最初に見つかった方法

 最初に以下の方法が見つかりました。しかし、スクリプトエディタ上からは動作するのですが、シェルからは動作しませんでした。

(() => {
    'use strict';
    let a = Application('System Events');
    a.includeStandardAdditions = true;
    return a.theClipboard();
})();

JavaScript for Automation: getting the clipboard - Technical Notes

 以下の例外が発生します。

osascript[19144:2059849] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSDictionaryM __setObject:forKey:]: object cannot be nil'

シェルから動作させる方法

 仕方がないので、doShellScript() を使って pbpaste 経由でクリップボード(Paste Board)のテキストを取得しました。

#!/usr/bin/osascript -l JavaScript
(() => {
    'use strict';
    var a = Application.currentApplication();
    a.includeStandardAdditions = true;
    return a.doShellScript('pbpaste');
})();

追記

 以下のコードでいけました。

#!/usr/bin/osascript -l JavaScript

(() => {
    'use strict';
    var a = Application.currentApplication(),
        sa = (a.includeStandardAdditions = true, a),
        strClip = sa.theClipboard();
    console.log(strClip);
})();

参考:JXA: Reading/Using Data from the Clipboard - Questions & Suggestions - Keyboard Maestro Discourse

環境

 以下の環境で動作確認しました。

ProductName:    Mac OS X
ProductVersion: 10.15.7
BuildVersion:   19H1323
AppleScript version: 2.7
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0