2011年8月17日水曜日

[AppleScript] 各ブラウザで最前面のページタイトルとURLを取得

タイトルどおりなんですが、それぞれで取り出す手法が違います。
AppleScriptでは、同じクラスでもアプリによって意味が違うことがあります。
なので、一つの情報を取り出すにも、同じ手段が取れないことはザラです。
Macで使う最近のブラウザといったら、Safari、Google Chrome、Firefoxでしょうか。
それ以外は使ってないので、ひとまずは3つ作りました。


まずはSafari。


tell application "Safari"
set page_URL to URL of current tab of window 1
set page_title to name of current tab of window 1
end tell

うん、分かりやすいですね。さすがApple純正ブラウザです。
用語説明を開いて驚いたんですが、印刷設定まで出来るんです。充実し過ぎ。


お次はGoogle Chrome。


tell application "Google Chrome"
set page_URL to URL of active tab of window 1
set page_title to title of active tab of window 1
end tell

まあ、大体は一緒ですね。currentがactiveになっただけ。
しかし、このくらいなら統一して欲しい気もしますが・・・
この辺りがAppleScriptらしさ。クラス云々というのはこういった側面です。


最後にFirefox。


tell application "Firefox"
activate
set page_title to the name of front window
tell application "System Events"
keystroke "l" using {command down}
keystroke "c" using {command down}
set page_URL to the clipboard as text
end tell
end tell

ええ、思わず「うそ・・・だろ・・・?」と言いたくなるコードです。
URL取得でkeystrokeとか、冗談でしか無いですね。が、残念。これしかありません。
AppleはMozillaに恨みでも買ってるんでしょうか。
細かく言えば、GUI Scriptingのエラー処理、クリップボードの保護も欲しいところです。
その辺を追加したらこうなります。


my gui_check()
set temp to the clipboard as text
tell application "Firefox"
activate
set page_title to the name of front window
tell application "System Events"
keystroke "l" using {command down}
keystroke "c" using {command down}
delay 0.5
set page_URL to the clipboard as text
end tell
end tell
delay 0.5
set the clipboard to temp as text

to gui_check()
tell application "System Events"
if UI elements enabled is false then
tell application "System Preferences"
activate
set current pane to pane "com.apple.preference.universalaccess"
set msg to "GUI scripting is not available." & return & "Do you put the check in" & return & "\"Enable access for assistive devices\" ?"
--display dialog msg buttons {"OK"} default button "OK" with icon note --giving up after 10
display dialog msg buttons {"cansel", "check and try"} with icon note
end tell
set UI elements enabled to true
delay 0.5
tell application "System Preferences" to quit
delay 0.5
end if
end tell
end gui_check

もうね、やってられっかって話です。
そして嫌味なのが、この手法だと3つのブラウザ全て共通で使えるということです。
3つのブラウザに対応した形を作るなら、これをハンドラにした方が楽だということ。
まあ、 絶 対 に やらないけど・・・


でもまあ、これでFirefoxでもURL取得のテンプレが出来たので、次からは楽できそう。
ついでにGUI Scriptingのエラーもルーチン化できたし。こっちは随分と便利。
にしても、もう少しなんとかならないかなぁ・・・
言語を変えれば解決するんでしょうか・・・
今回これを作るにあたって、少しSafariに傾きつつあります。

0 件のコメント:

コメントを投稿