Home About Contact
macOS , AppleScript , Note Taking

AppleScript を使って Safari から情報を得る

osascript を使えば Safari から URL や title そして本文コンテンツを取得できるので、それを試した。

page コマンド

osascript + curl + textutil で Safari からテキストを取得する。

#!/bin/bash
url=$(osascript \
  -e 'tell application "Safari"' \
  -e 'set theUrl to URL of document 1' \
  -e 'end tell' \
  -e 'return theUrl')

curl -s "$url" | textutil -stdin -stdout -format html -convert txt

これをパスの通った場所に page というファイル名で保存して chmod u+x page しておく。

そして、 safari でこのページ https://blog.mindboardapps.com/posts/nvim-kotlin-lsp/ を開いた状態から ターミナルで このスクリプトを実行すると Safari で今開いているページの内容(テキスト)が標準出力される。

$ page
 Home  About  Contact
Vim , Neovim
Sunday, June 21, 2026

Neovim への移行の試み
とくに vim で不満があるわけではない。ただなんとなく Neovim へ移行しようと考え始めた。 以前にも Neovim へ移行しようとしたとき・・・それは Neovim なら VSCode のように AI にコード支援してもらえる(vim だとそれができないのか?などは不明)らしいので・・・ しかし、そのときは nvim をターミナルで起動して色の問題でつまずき放置していた。

(以下省略)

これでテキストは取得できるのだが、 それとはまた別のページ https://www.reddit.com/r/google/comments/1tb9tto/google_completely_missed_the_point_googlebook/ を Safari で開いた状態で試すと、何も取得できない。

$ page

URL を得て その URL から curl -s してテキストを抜き出す方法はサイトによってはうまく機能しない。

tell application "Safari" するときに良く調べてみると(AIに訊ねただけですが)次のように (curl, textutil を使わなくとも)直接そのページのテキストを取得する方法が提供されていた。

このように:

osascript \
  -e 'tell application "Safari"' \
  -e 'set theText to text of document 1' \
  -e 'end tell' \
  -e 'return theText'

これで再度 page してみる:

$ page
Skip to main content
Google completely missed the point. (Googlebook) : r/google
Sign Up
Log In

Expand user menu

Go to google
r/google
•
3mo ago
TimeScarcity1949

Google completely missed the point. (Googlebook)

A few days ago, I thought that Aluminum OS could be a genuine competitor to Windows 11 in the desktop space. People were tired of Windows 11's AI, its bloat, and its genuine quick-and-dirty-ness.

(以下省略)

無事取得できた。

url だけ取得

osascript \
  -e 'tell application "Safari"' \
  -e 'set theUrl to URL of document 1' \
  -e 'end tell' \
  -e 'return theUrl'

実行:

https://blog.mindboardapps.com/posts/get-something-from-safari/

title だけ取得

osascript \
  -e 'tell application "Safari"' \
  -e 'set theName to name of document 1' \
  -e 'end tell' \
  -e 'return theName'

実行:

my notebook

まとめ

これと自前の Note Taking ツールを組み合わせると Safari で見ているページのテキストを emacs で編集する という機能が実現できそう。 (もちろん、URLに含まれる Note ID から該当ノートのテキストを取得する REST API などを用意する必要はある。 そして、もちろん 編集したテキストを更新する方法も用意しなければならない。)