LoginSignup
2
1

More than 3 years have passed since last update.

Chromeで開いているタブのURLをコマンドラインから取得する(macOS)

Last updated at Posted at 2021-01-19

AppleScriptを使って書いているので、macOS でしか動きません。
とりあえずzsh 5.8 (x86_64-apple-darwin19.6.0)GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin19) での動作を確認しています。

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.6

現在開いている Chrome の window の数を取得する

osascript -e 'tell application "Google Chrome" to get number of windows'

window で開いているタブの数を取得する

osascript -e 'tell application "Google Chrome" to get number of tabs in window 1'

タブの URL を取得する

osascript -e 'tell application "Google Chrome" to get URL of tab 1 of window 1'

よしなに書いてみる

#!/bin/sh

tell_chrome='tell application "Google Chrome"'

num_win=$(osascript -e "$tell_chrome to get number of windows")

for (( i=1; i<=num_win; i++ )); do
    num_tab=$(osascript -e "$tell_chrome to get number of tabs in window $i")
    echo "[$num_tab tabs in window $i]"
    for (( j=1; j<=num_tab; j++ )); do
        url=$(osascript -e "$tell_chrome to get URL of tab $j of window $i")
        echo "\t$url"
    done
    echo
done
実行結果
[2 tabs in window 1]
        chrome://newtab/
        https://qiita.com/

[1 tabs in window 2]
        file:///Users/hoge/huga/index.html

ちなみに

open -a "Google Chrome" https://qiita.com

これでChromeを直接開くことができます。

追記

アプリの起動

osascript -e 'tell application "Google Chrome" to activate'

アプリの終了

osascript -e 'tell application "Google Chrome" to quit'

window を閉じる

osascript -e 'tell application "Google Chrome" to close window 1'

すべての window を閉じる

osascript -e 'tell application "Google Chrome" to close every window'
2
1
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
2
1