【Apple Script】Safariブラウザの複数ウィンドウに対応する

Apple Script で Safari ブラウザを操作する時に、

当たり前のように、window 1 と document 1 としていた。

    tell application "Safari"
        tell window 1
        set val to do JavaScript "
            alert('test');
        " in document 1
        end tell
    end tell

window 1 の 「1」は、ウィンドウのインデックスで、

最前面のウィンドウが「1」となるようです。

ずっとこの設定で使っていたので、複数の Apple Script の同時実行できませんでした。

そこで、1つの実行につき、ウィンドウを1つ使うことにしました。

ウィンドウには、インデックス以外にもIDが存在するため、タブよりも扱いやすいと考えたからです。

まず、各プログラムに、

global gWinId

のグローバル変数を持たせ、

プログラム開始時に、以下の関数を実行。

on onLoad(args)
    set {} to args & {}
    --set {bounds_:aBounds} to args & {bounds_:{300, 50, 1200, 800}}

    tell application "Safari" to activate
    tell application "System Events"
        tell process "Safari"
            set frontmost to true
            click menu item "新規ウインドウ" of menu "ファイル" of menu bar 1
        end tell
    end tell

    tell application "Safari"
        --activate
        tell window 1
            set gWinId to id
            --set bounds to aBounds
        end tell

        log "gWinId = " & gWinId
    end tell
end onLoad

最前面に 該当の window が出てくるので、

ここから、global gWinId 変数 に、window の IDを保持する。

ウィンドウのIDからインデックスを取得する関数を作成。

on getWinIndex(args)
    set {} to args & {}
    tell application "Safari"
        repeat with winIndex from 1 to (count of (every window))
            if gWinId is (id of window winIndex) then
                --log "winId = " & gWinId
                --log "winIndex = " & winIndex
                return winIndex
            end if
        end repeat

        return -1

    end tell
end getWinIndex

do JavaScript の、in document の後ろで、その関数を呼び出す。

on alert(args)
    set {text_:aText} to args & {text_:""}
    tell application "Safari"
        set val to do JavaScript "
            alert('" & aText & "');
        " in document (my getWinIndex({}))
    end tell
end alert

メインのプログラムはこんな感じ。


global gWinId

on run argv

    my onLoad({})

    my alert({text_:"test"})

end run

・・・

これでマルチウィンドウに対応できる。

参考サイト