macOSでブラウザのURLを取得する方法

macOSでブラウザのURLを取得する方法

macOSにはAppleScript(osascript)というスクリプト言語が使えます。そのAppleScriptのコマンドを使えば今開いているブラウザURLを取得することができます。AppleScript利用するには、ターミナルでosascriptコマンドを使います。

SafariのURLを取得するには下記のコードです。

osascript -e 'tell app "safari" to get the url of the current tab of window 1'

Google ChromeのURLを取得する場合

osascript -e 'tell app "google chrome" to get the url of the active tab of window 1'

Swift macOS kCGWindowNameが出ない場合

Swift macOS kCGWindowNameが出ない場合

macOSアプリで、起動中の他のアプリ(Windw)の状態を列挙したい場合CGWindowListCopyWindowInfo()を使えば macOS上で起動しているWindowなどが列挙できます。下記はコード例です。

if let enumWindows = CGWindowListCopyWindowInfo([.optionAll], 0) {
	for windowInfo in enumWindows as NSArray {
		if let info = windowInfo as? NSDictionary {
			print("\(info)")
		}
	}
}

上記コードで、kCGWindowNumber・kCGWindowOwnerName・kCGWindowOwnerPID・kCGWindowBoundsなどの情報を取得することができます。しかし、kCGWindowNameは取得できないようです。kCGWindowNameを取得したい場合は、macOSの[システム環境設定|セキュリティーとプライバシー|画面収録]に開発中のアプリを登録することで、取得可能になります。

[システム環境設定|セキュリティーとプライバシー]
[システム環境設定|セキュリティーとプライバシー]
func getWindowText(_ windowInfo: NSDictionary) -> String {
	let windowName = windowInfo["kCGWindowName"]
	if (windowName != nil) {
		let windowText: String = windowName as! NSString as String
		return windowText
	} else {
		return ""
	}
}

func enumWindows() {
	if let enumWindows = CGWindowListCopyWindowInfo([.optionAll], 0) {
		for windowInfo in enumWindows as NSArray {
			if let info = windowInfo as? NSDictionary {
				let strWindowText:String = getWindowText(info)
				if (strWindowText.count > 0)  {
					print(strWindowText)
				}
			}
		}
	}
}

2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED