private static void Main(string[] args) { Task.Run(async() => { // synchronization var screenshotDone = new ManualResetEventSlim(); // STEP 1 - Run Chrome var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner()); using (var chromeProcess = chromeProcessFactory.Create(9222, true)) { // STEP 2 - Create a debugging session var sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault(); var chromeSessionFactory = new ChromeSessionFactory(); var chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl); chromeSession.Subscribe <DomContentEventFiredEvent>(domContentEvent => { System.Console.WriteLine("DomContentEvent: " + domContentEvent.Timestamp); }); chromeSession.SendAsync(new NavigateCommand { Url = "http://www.google.com" }).Wait(); } }).Wait(); }
private static void Main(string[] args) { // STEP 1 - Run Chrome var chromeProcessFactory = new ChromeProcessFactory(); using (var chromeProcess = chromeProcessFactory.Create(9222)) { // STEP 2 - Create a debugging session var endpointUrl = chromeProcess.GetSessions().Result.LastOrDefault(); var chromeSessionFactory = new ChromeSessionFactory(); var chromeSession = chromeSessionFactory.Create(endpointUrl); // STEP 3 - Send a command // // Here we are sending a command to tell chrome to navigate to // the specified URL var navigateResponse = chromeSession.SendAsync(new NavigateCommand { Url = "http://www.google.com" }) .Result; Console.WriteLine("NavigateResponse: " + navigateResponse.Id); // STEP 4 - Register for events (in this case, "Page" domain events) // send an event to tell chrome to send us all Page events // but we only subscribe to certain events in this session var pageEnableResult = chromeSession.SendAsync <ChromeDevTools.Protocol.Chrome.Page.EnableCommand>().Result; Console.WriteLine("PageEnable: " + pageEnableResult.Id); chromeSession.Subscribe <Protocol.Chrome.Page.DomContentEventFiredEvent>(domContentEvent => { Console.WriteLine("DomContentEvent: " + domContentEvent.Timestamp); }); // you might never see this, but that's what an event is ... right? chromeSession.Subscribe <Protocol.Chrome.Page.FrameStartedLoadingEvent>(frameStartedLoadingEvent => { Console.WriteLine("FrameStartedLoading: " + frameStartedLoadingEvent.FrameId); }); Console.ReadLine(); } }
private static void Main(string[] args) { Task.Run(async() => { // synchronization var screenshotDone = new ManualResetEventSlim(); // STEP 1 - Run Chrome var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner()); using (var chromeProcess = chromeProcessFactory.Create(9222, false)) { // STEP 2 - Create a debugging session var sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault(); var chromeSessionFactory = new CustomSessionFactory(); var chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl); ((ChromeMessageSession)chromeSession).SubscribeFinal(dynObj => { Console.WriteLine("Received generic object"); Console.WriteLine(JsonConvert.SerializeObject(dynObj)); }); chromeSession.Subscribe <BindingCalledEvent>(bindingEvent => { Console.WriteLine("Binding event called"); }); chromeSession.Subscribe <ExecutionContextCreatedEvent>(evt => { // we cannot block in event handler, hence the task Task.Run(async() => { Console.WriteLine("execution event received: " + DateTime.Now); //Attach to the target var tgtResp = await chromeSession.SendAsync(new AddBindingCommand { name = "selfie", executionContextId = evt.Context.Id }); Console.WriteLine("Bound to new execution context"); }); }); chromeSession.Subscribe <InspectRequestedEvent>(inspectEvent => { // we cannot block in event handler, hence the task Task.Run(async() => { Console.WriteLine("inspect event received: " + DateTime.Now); }); }); // STEP 3 - Send a command // // Here we are sending a commands to tell chrome to set the viewport size // and navigate to the specified URL await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand { Width = ViewPortWidth, Height = ViewPortHeight, Scale = 1 }); var navigateResponse = await chromeSession.SendAsync(new NavigateCommand { Url = "https://www.google.com" }); Console.WriteLine("NavigateResponse: " + navigateResponse.Id); // STEP 4 - Register for events (in this case, "Page" domain events) // send an command to tell chrome to send us all Page events // but we only subscribe to certain events in this session var runtimeResult = await chromeSession.SendAsync <MasterDevs.ChromeDevTools.Protocol.Chrome.Runtime.EnableCommand>(); var targetResp = await chromeSession.SendAsync(new GetTargetsCommand()); string tgtId = null; foreach (var tgt in targetResp.Result.TargetInfos) { if (tgt.Type.Equals("page", StringComparison.InvariantCultureIgnoreCase)) { var tgtAttach = await chromeSession.SendAsync(new AttachToTargetCommand { TargetId = tgt.TargetId }); Console.WriteLine($"Target {tgt.TargetId} attached: {tgtAttach.Result.SessionId}"); tgtId = tgt.TargetId; } } var bindResp = await chromeSession.SendAsync(new AddBindingCommand { name = "selfie" }); Console.WriteLine("Bound to new execution context"); // wait for screenshoting thread to (start and) finish screenshotDone.Wait(); Console.WriteLine("Exiting .."); } }).Wait(); }
async private void dockIt() { // STEP 1 - Run Chrome var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner()); var chromeProcess = chromeProcessFactory.Create(9401, false, "176.53.142.238:8000", null, "http"); //var chromeProcess = chromeProcessFactory.Create(9504, false, null, "jniherujherfjio"); //var chromeProcess1 = chromeProcessFactory.Create(9504, false); Process pr = ((RemoteChromeProcess)chromeProcess).Process; // STEP 2 - Create a debugging session var sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault(); var chromeSessionFactory = new ChromeSessionFactory(); chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl); //Process pr = Process.Start("notepad.exe"); if (hWndDocked != IntPtr.Zero) //don't do anything if there's already a window docked. { return; } try { var navigateResponse = await chromeSession.SendAsync(new NavigateCommand { //Url = "https://google.com" Url = "about:blank" }); } catch (Exception ex) { Console.WriteLine(ex); } childHandles = null; pDocked = pr; procId = pr.Id; while (hWndDocked == IntPtr.Zero) { pDocked.WaitForInputIdle(1000); //wait for the window to be ready for input; pDocked.Refresh(); //update process info if (pDocked.HasExited) { return; //abort if the process finished before we got a handle. } hWndDocked = pDocked.MainWindowHandle; //cache the window handle //var proceeses=pDocked. childHandles = GetAllChildHandles(hWndDocked); } //Windows API call to change the parent of the target window. //It returns the hWnd of the window's parent prior to this call. hWndOriginalParent = SetParent(hWndDocked, pannel.Handle); //hWndOriginalParent = SetParent(childHandles[1], pannel.Handle); //Wire up the event to keep the window sized to match the control SizeChanged += window_SizeChanged; //Perform an initial call to set the size. AlignToPannel(); //enable network var enableNetwork = await chromeSession.SendAsync(new Chrome.Network.EnableCommand()); await Task.Delay(1000); //var navigateResponse = await chromeSession.SendAsync(new NavigateCommand //{ // Url = "https://google.com" //}); //await Task.Delay(3000); }
static void Main(string[] args) { Task.Run(async() => { // STEP 1 - Run Chrome var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner()); //var chromeProcess = chromeProcessFactory.Create(9226, true); var chromeProcess = chromeProcessFactory.Create(9401, false, "45.133.32.223:8000", null, "socks5"); // STEP 2 - Create a debugging session var sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault(); var chromeSessionFactory = new ChromeSessionFactory(); IChromeSession chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl); chromeSession.Subscribe <DataReceivedEvent>(dataReceivedEvent => { DataReceivedEventHandler(dataReceivedEvent); }); chromeSession.Subscribe <EventSourceMessageReceivedEvent>(eventSourceMessageReceivedEvent => { EventSourceMessageReceivedEventHandler(eventSourceMessageReceivedEvent); }); chromeSession.Subscribe <RequestWillBeSentEvent>(requestWillBeSentEvent => { RequestWillBeSentEventHandler(requestWillBeSentEvent); }); chromeSession.Subscribe <RequestPausedEvent>(requestPausedEvent => { RequestPausedEventHandler(requestPausedEvent, chromeSession); }); chromeSession.Subscribe <AuthRequiredEvent>(authRequiredEvent => { AuthRequiredEventHandler(authRequiredEvent, chromeSession); }); // STEP 3 - Send a command // // Here we are sending a commands to tell chrome to set the viewport size // and navigate to the specified URL await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand { Width = ViewPortWidth, Height = ViewPortHeight, Scale = 1 }); //enable network var enableNetwork = await chromeSession.SendAsync(new Chrome.Network.EnableCommand()); //proxy auth await ProxyAuthenticate(proxyUser, proxyPass, chromeSession); var navigateResponse = await chromeSession.SendAsync(new NavigateCommand { Url = "http://mybot.su/webrtcleak.php" }); await Task.Delay(3000); Console.WriteLine("NavigateResponse: " + navigateResponse.Id); await Task.Delay(10000); Console.ReadKey(); chromeProcess.Dispose(); }).Wait(); }
private static void Main(string[] args) { Task.Run(async() => { // synchronization var screenshotDone = new ManualResetEventSlim(); // STEP 1 - Run Chrome var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner()); using (var chromeProcess = chromeProcessFactory.Create(9222, true)) { // STEP 2 - Create a debugging session var sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault(); var chromeSessionFactory = new ChromeSessionFactory(); var chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl); // STEP 3 - Send a command // // Here we are sending a commands to tell chrome to set the viewport size // and navigate to the specified URL await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand { Width = ViewPortWidth, Height = ViewPortHeight, Scale = 1 }); var navigateResponse = await chromeSession.SendAsync(new NavigateCommand { Url = "http://www.google.com" }); Console.WriteLine("NavigateResponse: " + navigateResponse.Id); // STEP 4 - Register for events (in this case, "Page" domain events) // send an command to tell chrome to send us all Page events // but we only subscribe to certain events in this session var pageEnableResult = await chromeSession.SendAsync <Protocol.Chrome.Page.EnableCommand>(); Console.WriteLine("PageEnable: " + pageEnableResult.Id); chromeSession.Subscribe <LoadEventFiredEvent>(loadEventFired => { // we cannot block in event handler, hence the task Task.Run(async() => { Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp); var documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root.NodeId; var bodyNodeId = (await chromeSession.SendAsync(new QuerySelectorCommand { NodeId = documentNodeId, Selector = "body" })).Result.NodeId; var height = (await chromeSession.SendAsync(new GetBoxModelCommand { NodeId = bodyNodeId })).Result.Model.Height; await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand { Width = ViewPortWidth, Height = height, Scale = 1 }); Console.WriteLine("Taking screenshot"); var screenshot = await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" }); var data = Convert.FromBase64String(screenshot.Result.Data); File.WriteAllBytes("output.png", data); Console.WriteLine("Screenshot stored"); // tell the main thread we are done screenshotDone.Set(); }); }); // wait for screenshoting thread to (start and) finish screenshotDone.Wait(); Console.WriteLine("Exiting .."); } }).Wait(); }
} // End Sub NotMain public static async System.Threading.Tasks.Task runVote() { // synchronization System.Threading.ManualResetEventSlim screenshotDone = new System.Threading.ManualResetEventSlim(); // STEP 1 - Run Chrome IChromeProcessFactory chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner()); using (IChromeProcess chromeProcess = chromeProcessFactory.Create(9222, true)) { // STEP 2 - Create a debugging session ChromeSessionInfo[] sessionInfos = await chromeProcess.GetSessionInfo(); ChromeSessionInfo sessionInfo = (sessionInfos != null && sessionInfos.Length > 0) ? sessionInfos[sessionInfos.Length - 1] : new ChromeSessionInfo(); IChromeSessionFactory chromeSessionFactory = new ChromeSessionFactory(); IChromeSession chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl); CommandResponse <ClearBrowserCacheCommandResponse> clearCache = await chromeSession.SendAsync(new ClearBrowserCacheCommand()); System.Console.WriteLine(clearCache.Result); CommandResponse <ClearBrowserCookiesCommandResponse> clearCookies = await chromeSession.SendAsync(new ClearBrowserCookiesCommand()); System.Console.WriteLine(clearCookies.Result); // CommandResponse<ClearObjectStoreCommandResponse> clearObjectStorage = await chromeSession.SendAsync(new ClearObjectStoreCommand()); // System.Console.WriteLine(clearObjectStorage.Result); // CommandResponse<ClearDataForOriginCommandResponse> clearStorage = await chromeSession.SendAsync(new ClearDataForOriginCommand() { Origin= "www.20min.ch", StorageTypes = "all" }); // Whatever the correct command for clear everything is... await ClearData(chromeSession, "www.20min.ch", "all"); await ClearData(chromeSession, "20min.ch", "all"); await ClearData(chromeSession, "*", "all"); await ClearData(chromeSession, "all", "all"); // STEP 3 - Send a command // // Here we are sending a commands to tell chrome to set the viewport size // and navigate to the specified URL await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand { Width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width, Height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height, Scale = 1 }); CommandResponse <NavigateCommandResponse> navigateResponse = await chromeSession.SendAsync(new NavigateCommand { // Url = "http://www.google.com" // Url = "about:blank" Url = "https://www.20min.ch/schweiz/news/story/GA-wird-teurer--kein-Studentenrabatt-mehr-27426069" }); System.Console.WriteLine("NavigateResponse: " + navigateResponse.Id); // STEP 4 - Register for events (in this case, "Page" domain events) // send an command to tell chrome to send us all Page events // but we only subscribe to certain events in this session ICommandResponse pageEnableResult = await chromeSession.SendAsync <MasterDevs.ChromeDevTools.Protocol.Chrome.Page.EnableCommand>(); System.Console.WriteLine("PageEnable: " + pageEnableResult.Id); chromeSession.Subscribe <LoadEventFiredEvent>(loadEventFired => { // we cannot block in event handler, hence the task System.Threading.Tasks.Task2.Run(async() => { System.Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp); /* * long documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root.NodeId; * long bodyNodeId = * (await chromeSession.SendAsync(new QuerySelectorCommand * { * NodeId = documentNodeId, * Selector = "body" * })).Result.NodeId; * * long height = (await chromeSession.SendAsync(new GetBoxModelCommand { NodeId = bodyNodeId })).Result.Model.Height; */ CommandResponse <EvaluateCommandResponse> removePopOver = await chromeSession.SendAsync(new EvaluateCommand { Expression = @" window.setTimeout(function(){ var one = document.getElementById('onesignal-popover-cancel-button'); if(one != null) one.click(); }, 2000); /* window.setTimeout(function(){ window.close(); }, 4000); */ ", // ContextId = 123 }); CommandResponse <EvaluateCommandResponse> closeWindow = await chromeSession.SendAsync(new EvaluateCommand { // <a href="javascript:window.close(self);">run</a> Expression = @" console.log('closing'); var a = document.createElement('a'); var linkText = document.createTextNode('T'); a.id = 'lolz'; a.appendChild(linkText); a.href = 'javascript:window.close(self);'; document.body.appendChild(a); document.getElementById('lolz').click(); // window.close(); // open(location, '_self').close(); " // ContextId = 123 , UserGesture = true }); System.Console.WriteLine(closeWindow.Result); System.Console.WriteLine("Closing page"); var closeTargetResponse = chromeSession.SendAsync( new CloseTargetCommand() { TargetId = navigateResponse.Result.FrameId } ); /* * MasterDevs.ChromeDevTools.CommandResponse<CloseTargetCommandResponse> closeTargetResponse = * await chromeSession.SendAsync( * new CloseTargetCommand() * { * TargetId = navigateResponse.Result.FrameId * } * ); */ System.Console.WriteLine("Page closed"); System.Console.WriteLine(closeTargetResponse); if (true) { // document.querySelector("#thread3367_msg3367 > div.rate_button > div.clickable.top").click() // document.querySelector("#thread3367_msg3367 > div.rate_button > div.clickable.bottom").click() string threadId = "3399"; string msgId = "3399"; string voteDirection = "bottom"; // top / bottom string votingElement = "#thread" + threadId + "_msg" + msgId + @" > div.rate_button > div.clickable." + voteDirection; string javaScriptToExecute = @" (function() { var elmnt = document.querySelector('" + votingElement + @"'); if (elmnt != null) { elmnt.scrollIntoView(); window.scrollBy(0, -70) elmnt.click(); console.log('https://www.youtube.com/watch?v=h6mJw50OdZ4&t=163'); console.log('The first honest vote ever in a rotten borough !'); console.log('CopyLeft 2019 StS'); } })(); "; CommandResponse <EvaluateCommandResponse> evr = await chromeSession.SendAsync(new EvaluateCommand { Expression = javaScriptToExecute, // ContextId = 123 }); if (evr.Result.ExceptionDetails != null) { System.Console.WriteLine(evr.Result.ExceptionDetails); } else { System.Console.WriteLine("voted"); } } await System.Threading.Tasks.Task2.Delay(3000); // tell the main thread we are done screenshotDone.Set(); }); }); // End Sub LoadEventFired // wait for screenshoting thread to (start and) finish screenshotDone.Wait(); System.Console.WriteLine("Exiting .."); } // End Using chromeProcess } // End Sub Main(string[] args)
private static void Main(string[] args) { // synchronization var screenshotDone = new ManualResetEventSlim(); // STEP 1 - Run Chrome var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner()); var chromeProcess = chromeProcessFactory.Create(9401, false); Process pr = ((RemoteChromeProcess)chromeProcess).Process; // STEP 2 - Create a debugging session var sessionInfoArray = chromeProcess.GetSessionInfo().Result; var sessionInfo = sessionInfoArray.LastOrDefault(); var chromeSessionFactory = new ChromeSessionFactory(); IChromeSession chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl, pr); Task.Run(async() => { /* * ProcessStartInfo psiOpt = new ProcessStartInfo("cmd.exe", "/C netstat -a -n -o"); * psiOpt.WindowStyle = ProcessWindowStyle.Hidden; * psiOpt.RedirectStandardOutput = true; * psiOpt.UseShellExecute = false; * psiOpt.CreateNoWindow = true; * // запускаем процесс * Process procCommand = Process.Start(psiOpt); * // получаем ответ запущенного процесса * StreamReader srIncoming = procCommand.StandardOutput; * // выводим результат * string[] ss = srIncoming.ReadToEnd().Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); * StringCollection procStr = new StringCollection(); * foreach (string s in ss) * { * if (s.Contains("9222")) * { * * string[] parts = s.Split(null); * int lenght = parts.Length; * int pid = Int32.Parse(parts[lenght - 1]); * var proc = Process.GetProcessById(pid); * //proc.Kill(); * procStr.Add(s); * } * * * } * * Console.WriteLine(srIncoming.ReadToEnd()); * // закрываем процесс * procCommand.WaitForExit();*/ //cookies var ccs = await chromeSession.SendAsync(new Protocol.Chrome.Network.GetAllCookiesCommand()); //await chromeSession.SendAsync(new Protocol.Chrome.Network.ClearBrowserCookiesCommand()); // STEP 3 - Send a command // // Here we are sending a commands to tell chrome to set the viewport size // and navigate to the specified URL await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand { Width = ViewPortWidth, Height = ViewPortHeight, Scale = 1 }); //enable network var enableNetwork = await chromeSession.SendAsync(new Protocol.Chrome.Network.EnableCommand()); var navigateResponse = await chromeSession.SendAsync(new NavigateCommand { Url = "http://mybot.su/login.php" }); await Task.Delay(3000); Console.WriteLine("NavigateResponse: " + navigateResponse.Id); // STEP 4 - Register for events (in this case, "Page" domain events) // send an command to tell chrome to send us all Page events // but we only subscribe to certain events in this session var pageEnableResult = await chromeSession.SendAsync <Protocol.Chrome.Page.EnableCommand>(); Console.WriteLine("PageEnable: " + pageEnableResult.Id); Console.WriteLine("Taking screenshot"); var screenshot = await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" }); var data = Convert.FromBase64String(screenshot.Result.Data); File.WriteAllBytes("output.png", data); Console.WriteLine("Screenshot stored"); /* * chromeSession.Subscribe<LoadEventFiredEvent>(loadEventFired => * { * // we cannot block in event handler, hence the task * Task.Run(async () => * { * Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp); * * var documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root.NodeId; * var bodyNodeId = * (await chromeSession.SendAsync(new QuerySelectorCommand * { * NodeId = documentNodeId, * Selector = "body" * })).Result.NodeId; * var height = (await chromeSession.SendAsync(new GetBoxModelCommand { NodeId = bodyNodeId })).Result.Model.Height; * * await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand * { * Width = ViewPortWidth, * Height = height, * Scale = 1 * }); * * await Task.Delay(1000); * * Console.WriteLine("Taking screenshot"); * var screenshot = await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" }); * * var data = Convert.FromBase64String(screenshot.Result.Data); * File.WriteAllBytes("output.png", data); * Console.WriteLine("Screenshot stored"); * * // tell the main thread we are done * screenshotDone.Set(); * }); * });*/ // wait for screenshoting thread to (start and) finish //screenshotDone.Wait(); ICommandResponse cr = chromeSession.SendAsync <GetDocumentCommand>().Result; long docNodeId = ((CommandResponse <GetDocumentCommandResponse>)cr).Result.Root.NodeId; //var dom = Protocol.Chrome.DOM.GetDocumentCommand(); var qs = chromeSession.SendAsync(new QuerySelectorCommand { NodeId = docNodeId, Selector = "#login_input_username" }).Result; var emailNodeId = qs.Result.NodeId; var sv = chromeSession.SendAsync(new FocusCommand { NodeId = emailNodeId }); var it = chromeSession.SendAsync(new ChromeDevTools.Protocol.Chrome.Input.InsertTextCommand { Text = "*****@*****.**" }); //pwd var qsPwd = chromeSession.SendAsync(new QuerySelectorCommand { NodeId = docNodeId, Selector = "#login_input_password" }).Result; var pwdNodeId = qsPwd.Result.NodeId; var svPwd = chromeSession.SendAsync(new FocusCommand { NodeId = pwdNodeId }); var itPwd = chromeSession.SendAsync(new ChromeDevTools.Protocol.Chrome.Input.InsertTextCommand { Text = "qwerty" }); await Task.Delay(1000); Console.WriteLine("Taking screenshot 2"); var screenshot2 = await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" }); var data2 = Convert.FromBase64String(screenshot2.Result.Data); File.WriteAllBytes("output2.png", data2); Console.WriteLine("Screenshot 2 stored"); //click button var qsButton = chromeSession.SendAsync(new QuerySelectorCommand { NodeId = docNodeId, Selector = "body:nth-child(2) div.container:nth-child(1) form:nth-child(21) > button.btn.btn-default:nth-child(4)" }).Result; var buttonNodeId = qsButton.Result.NodeId; Console.WriteLine("buttonNodeId " + buttonNodeId); ///take screenshot button /// string pathToScreenshot = GetElementScreenshot(buttonNodeId, chromeSession); var buttonBox = chromeSession.SendAsync(new GetBoxModelCommand { NodeId = buttonNodeId }); var buttonBoxRes = buttonBox.Result.Result.Model; double leftBegin = buttonBoxRes.Border[0]; double leftEnd = buttonBoxRes.Border[2]; double topBegin = buttonBoxRes.Border[1]; double topEnd = buttonBoxRes.Border[5]; double x = Math.Round((leftBegin + leftEnd) / 2, 2); double y = Math.Round((topBegin + topEnd) / 2, 2); try { var click = chromeSession.SendAsync(new ChromeDevTools.Protocol.Chrome.Input.DispatchMouseEventCommand { Type = "mousePressed", X = x, Y = y, ClickCount = 1, Button = "left" }); await Task.Delay(100); var clickReleased = chromeSession.SendAsync(new ChromeDevTools.Protocol.Chrome.Input.DispatchMouseEventCommand { Type = "mouseReleased", X = x, Y = y, ClickCount = 1, Button = "left" }); Console.WriteLine("midle " + x + " " + y); } catch (Exception ex) { Console.WriteLine(ex.Message); } await Task.Delay(5000); await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand { Width = ViewPortWidth, Height = ViewPortHeight, Scale = 1 }); Console.WriteLine("Taking screenshot 3"); var screenshot3 = await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" }); var data3 = Convert.FromBase64String(screenshot3.Result.Data); File.WriteAllBytes("output3.png", data3); Console.WriteLine("Screenshot 3 stored"); //scrolling /* * ICommandResponse cr_ = chromeSession.SendAsync<GetDocumentCommand>().Result; * long docNodeId2 = ((CommandResponse<GetDocumentCommandResponse>)cr_).Result.Root.NodeId; * * var bodyNodeId2 = * (await chromeSession.SendAsync(new QuerySelectorCommand * { * NodeId = docNodeId2, * Selector = "body" * })).Result.NodeId; * * var fc = chromeSession.SendAsync(new FocusCommand * { * NodeId = bodyNodeId2 * });*/ await Task.Delay(100); var scroll = chromeSession.SendAsync(new ChromeDevTools.Protocol.Chrome.Input.DispatchMouseEventCommand { Type = "mouseWheel", X = x, Y = y, DeltaX = 0, DeltaY = 10000 }); await Task.Delay(1000); Console.WriteLine("Taking screenshot 4"); var screenshot4 = await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" }); var data4 = Convert.FromBase64String(screenshot4.Result.Data); File.WriteAllBytes("output4.png", data4); Console.WriteLine("Screenshot 4 stored"); //cookies var cookies = (await chromeSession.SendAsync(new Protocol.Chrome.Network.GetAllCookiesCommand())).Result.Cookies; //cookies to json string format var json = Newtonsoft.Json.JsonConvert.SerializeObject(cookies); //delete cookies await chromeSession.SendAsync(new Protocol.Chrome.Network.ClearBrowserCookiesCommand()); //check delete cookies var cookiesForCheck = (await chromeSession.SendAsync(new Protocol.Chrome.Network.GetAllCookiesCommand())).Result.Cookies; var navigateResponse2 = await chromeSession.SendAsync(new NavigateCommand { Url = "http://mybot.su/login.php" }); Console.WriteLine("Taking screenshot 5"); var screenshot5 = await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" }); var data5 = Convert.FromBase64String(screenshot5.Result.Data); File.WriteAllBytes("output5.png", data5); Console.WriteLine("Screenshot 5 stored"); //deserialise cookies //set cookies JArray ja = JArray.Parse(json); List <Protocol.Chrome.Network.Cookie> cookiesList = new List <Protocol.Chrome.Network.Cookie>(); foreach (var cookie in ja) { Console.WriteLine(cookie["Name"]); Console.WriteLine(cookie["Value"]); Console.WriteLine(cookie["Domain"]); Console.WriteLine(cookie["Path"]); Console.WriteLine(cookie["Expires"]); Console.WriteLine(cookie["Size"]); Console.WriteLine(cookie["HttpOnly"]); Console.WriteLine(cookie["Secure"]); Console.WriteLine(cookie["Session"]); Console.WriteLine(cookie["SameSite"]); double expires = Double.Parse(cookie["Expires"].ToString()); bool secure = (cookie["Secure"].ToString() == "true") ? true : false; bool httpOnly = (cookie["HttpOnly"].ToString() == "true") ? true : false; var setCookie = await chromeSession.SendAsync(new Protocol.Chrome.Network.SetCookieCommand { Name = cookie["Name"].ToString(), Value = cookie["Value"].ToString(), Domain = cookie["Domain"].ToString(), Path = cookie["Path"].ToString(), Secure = secure, HttpOnly = httpOnly, SameSite = cookie["SameSite"].ToString(), Expires = expires }); } await Task.Delay(1000); //check cookies settings var cookiesForCheck2 = (await chromeSession.SendAsync(new Protocol.Chrome.Network.GetAllCookiesCommand())).Result.Cookies; var navigateResponse3 = await chromeSession.SendAsync(new NavigateCommand { Url = "http://mybot.su/login.php" }); Console.WriteLine("Taking screenshot 6"); var screenshot6 = await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" }); var data6 = Convert.FromBase64String(screenshot6.Result.Data); File.WriteAllBytes("output6.png", data6); Console.WriteLine("Screenshot 6 stored"); Console.WriteLine("Exiting .."); //await chromeSession.SendAsync(new Protocol.Chrome.Network.ClearBrowserCookiesCommand()); await Task.Delay(3000); }).Wait(); chromeProcess.Dispose(); }
async public Task <CallResult <IChromeSession> > GetChromeSession(string proxisString, string ua, string proxyProtocol, bool isDebug = false, bool headless = true, string profilePath = null) { L.Trace(); CallResult <IChromeSession> chromeSessionResult = new CallResult <IChromeSession>(); Proxy proxy = (proxisString != null && !String.IsNullOrWhiteSpace(proxisString)) ? new Proxy(proxisString) : null; this.isDebug = isDebug; var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner()); port = GetFreeLocalPort(); try { if (proxy != null) { string ipPort = proxy.Ip + ":" + proxy.Port; chromeProcess = chromeProcessFactory.Create(port, headless, ipPort, profilePath, proxyProtocol); } else { chromeProcess = chromeProcessFactory.Create(port, headless, null, profilePath, proxyProtocol); } var sessionInfoArray = await chromeProcess.GetSessionInfo(); var sessionInfo = sessionInfoArray.LastOrDefault(); var chromeSessionFactory = new ChromeSessionFactory(); chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl); chromeSession.Subscribe <RequestPausedEvent>(requestPausedEvent => { RequestPausedEventHandler(requestPausedEvent); }); chromeSession.Subscribe <AuthRequiredEvent>(authRequiredEvent => { AuthRequiredEventHandler(authRequiredEvent); }); chromeSession.Subscribe <FrameNavigatedEvent>(frameNavigatedEvent => { FrameNavigatedEventHandler(frameNavigatedEvent); }); chromeSession.Subscribe <LoadingFinishedEvent>(loadingFinishedEvent => { LoadingFinishedEventHandler(loadingFinishedEvent); }); /* * await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand * { * Width = GlobalVars.ViewPortWidth, * Height = GlobalVars.ViewPortHeight, * Scale = 1 * });*/ /* * //Target.setDiscoverTargets * var setDiscoverTargetsResult = await chromeSession.SendAsync(new Chrome.Target.SetDiscoverTargetsCommand * { * Discover=true * }); * //Target.createTarget * var createTargetResult = await chromeSession.SendAsync(new Chrome.Target.CreateTargetCommand * { * Url= "about:blank" * }); * string targetId = createTargetResult.Result.TargetId; * //Target.attachToTarget * var attachToTargetResult = await chromeSession.SendAsync(new Chrome.Target.AttachToTargetCommand * { * TargetId = targetId, * Flatten=true * * }); * string sessionId = attachToTargetResult.Result.SessionId; * chromeSession.MainSessionId = sessionId;*/ //enable page var pageEnableResult = await chromeSession.SendAsync <Chrome.Page.EnableCommand>(); //Page.getFrameTree var getFrameTreeResult = await chromeSession.SendAsync <Chrome.Page.GetFrameTreeCommand>(); //Target.setAutoAttach var setAutoAttachResult = await chromeSession.SendAsync(new Chrome.Target.SetAutoAttachCommand { AutoAttach = true, WaitForDebuggerOnStart = false, Flatten = true }); //Performance.enable var performanceEnableResult = await chromeSession.SendAsync <Chrome.Performance.EnableCommand>(); //enable network var enableNetwork = await chromeSession.SendAsync(new Chrome.Network.EnableCommand()); } catch (Exception ex) { chromeSessionResult.Error = new UsefulThings.Error(ex.Message); return(chromeSessionResult); } await Task.Delay(1000); //proxy auth if (proxy != null) { if (!String.IsNullOrWhiteSpace(proxy.Login)) { await ProxyAuthenticate(proxy.Login, proxy.Pwd); } } await SetUA(ua); chromeSessionResult.Data = chromeSession; return(chromeSessionResult); }
} // End Sub KillHeadless private static void Main(string[] args) { KillHeadless(); Task.Run(async() => { // synchronization System.Threading.ManualResetEventSlim screenshotDone = new System.Threading.ManualResetEventSlim(); // STEP 1 - Run Chrome IChromeProcessFactory chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner()); using (IChromeProcess chromeProcess = chromeProcessFactory.Create(9222, true)) { // STEP 2 - Create a debugging session //ChromeSessionInfo sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault(); ChromeSessionInfo[] sessionInfos = await chromeProcess.GetSessionInfo(); ChromeSessionInfo sessionInfo = (sessionInfos != null && sessionInfos.Length > 0) ? sessionInfos[sessionInfos.Length - 1] : new ChromeSessionInfo(); IChromeSessionFactory chromeSessionFactory = new ChromeSessionFactory(); IChromeSession chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl); // STEP 3 - Send a command // // Here we are sending a commands to tell chrome to set the viewport size // and navigate to the specified URL await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand { Width = ViewPortWidth, Height = ViewPortHeight, Scale = 1 }); var navigateResponse = await chromeSession.SendAsync(new NavigateCommand { Url = "http://www.google.com" }); System.Console.WriteLine("NavigateResponse: " + navigateResponse.Id); // STEP 4 - Register for events (in this case, "Page" domain events) // send an command to tell chrome to send us all Page events // but we only subscribe to certain events in this session ICommandResponse pageEnableResult = await chromeSession.SendAsync <Protocol.Chrome.Page.EnableCommand>(); System.Console.WriteLine("PageEnable: " + pageEnableResult.Id); chromeSession.Subscribe <LoadEventFiredEvent>(loadEventFired => { // we cannot block in event handler, hence the task Task.Run(async() => { System.Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp); long documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root.NodeId; long bodyNodeId = (await chromeSession.SendAsync(new QuerySelectorCommand { NodeId = documentNodeId, Selector = "body" })).Result.NodeId; long height = (await chromeSession.SendAsync(new GetBoxModelCommand { NodeId = bodyNodeId })).Result.Model.Height; await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand { Width = ViewPortWidth, Height = height, Scale = 1 }); System.Console.WriteLine("Taking screenshot"); var screenshot = await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" }); byte[] data = System.Convert.FromBase64String(screenshot.Result.Data); System.IO.File.WriteAllBytes("output.png", data); System.Console.WriteLine("Screenshot stored"); PrintToPDFCommand printCommand = new PrintToPDFCommand() { Scale = 1, MarginTop = 0, MarginLeft = 0, MarginRight = 0, MarginBottom = 0, PrintBackground = true, Landscape = false, PaperWidth = cm2inch(21), PaperHeight = cm2inch(29.7) }; System.Console.WriteLine("Printing PDF"); CommandResponse <PrintToPDFCommandResponse> pdf = await chromeSession.SendAsync(printCommand); System.Console.WriteLine("PDF printed."); byte[] pdfData = System.Convert.FromBase64String(pdf.Result.Data); System.IO.File.WriteAllBytes("output.pdf", pdfData); System.Console.WriteLine("PDF stored"); // tell the main thread we are done screenshotDone.Set(); }); }); // wait for screenshoting thread to (start and) finish System.Console.WriteLine("Exiting .."); screenshotDone.Wait(); } }).Wait(); }