; Written by AHK_User 2019-10-11
; Special thanks to tmplinshi, CH HAN and Joe Glines
; https://www.autohotkey.com/boards/viewtopic.php?f=7&t=32323&p=296136&hilit=schrome_get#p296136
;Driver := SChrome_Get("https://stackoverflow.com/questions/37088589/selenium-wont-open-a-new-url-in-a-new-tab-python-chrome/39353910#39353910",,"Tab")

; Written by AHK_User 2019-10-11
; Special thanks to tmplinshi, CH HAN and Joe Glines

SChrome_Get(URL := "", Profile := "Profile 1", IP_Port := "127.0.0.1:9222"){
	IP_Port_Nr := RegExReplace(IP_Port, ".*:(\d*)", "$1")
	if WinExist("ahk_exe Chrome.exe"){
		WinGet, pid, PID, ahk_exe chrome.exe
		for item in ComObjGet("winmgmts:").ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId='" pid "'"){
			if RegExMatch(item.CommandLine, "i)--remote-debugging-port=\K\d+", port){
				break
			}
		}
		if (Port=""){
			MsgBox, 36, ,Chrome Needs to be started in debugging mode in order for Autohotkey to connect to it.`nIs it ok to restart Chrome in debugmode to enable a connection?
			IfMsgBox, Yes
			{
				While(WinExist("ahk_exe chrome.exe")) {
					WinClose, ahk_exe chrome.exe
				}
				Process, WaitClose, chrome.exe
			}
			Else{
				Exit
			}
		}
	}
	
	if(URL!="" or !winExist("ahk_class Chrome_WidgetWin_1")){
		; run % "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --remote-debugging-port=" IP_Port_Nr ( winExist("ahk_class Chrome_WidgetWin_1") ? " --new-window " : " " ) URL
		if(A_ComputerName = "WLatitude")
		{
			run, C:\Software\Chromium\chrome.exe --remote-debugging-port=%IP_Port_Nr% --profile-directory="%Profile%" ; %URL%
			; sleep, 1000
			; run, C:\Software\Chromium\chrome.exe --remote-debugging-port=%IP_Port_Nr% --profile-directory="%Profile%" --new-window %URL%
		}
		else, 
			{
				run, chrome.exe --remote-debugging-port=%IP_Port_Nr% --profile-directory="%Profile%" %URL%
				; sleep, 1000
				; run, chrome.exe --remote-debugging-port=%IP_Port_Nr% --profile-directory="%Profile%" --new-window %URL%

			}
	}
	
	Driver := ComObjCreate("Selenium.ChromeDriver")
	Driver.SetCapability("debuggerAddress", IP_Port)
	Driver.Start()
	return Driver
}