public static async Task <IChromeSession> Create() { var chromeProcessFactory = new CefFactory(); icp = chromeProcessFactory.Create(Port, true); var sessionInfo = (await icp.GetSessionInfo()).LastOrDefault(); var chromeSessionFactory = new ChromeSessionFactory(); var chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl); await chromeSession.SendAsync(new MasterDevs.ChromeDevTools.Protocol.Chrome.Network.EnableCommand { MaxPostDataSize = 65536 }); await chromeSession.SendAsync <MasterDevs.ChromeDevTools.Protocol.Chrome.Page.EnableCommand>(); await chromeSession.SendAsync <MasterDevs.ChromeDevTools.Protocol.Chrome.DOM.EnableCommand>(); await chromeSession.SendAsync(new MasterDevs.ChromeDevTools.Protocol.Chrome.Debugger.EnableCommand { MaxScriptsCacheSize = 10000000 }); await chromeSession.SendAsync(new MasterDevs.ChromeDevTools.Protocol.Chrome.Target.SetAutoAttachCommand { AutoAttach = true, WaitForDebuggerOnStart = true, Flatten = true, }); await chromeSession.SendAsync <MasterDevs.ChromeDevTools.Protocol.Chrome.Runtime.EnableCommand>(); await chromeSession.SendAsync <MasterDevs.ChromeDevTools.Protocol.Chrome.Runtime.RunIfWaitingForDebuggerCommand>(); await chromeSession.SendAsync(new MasterDevs.ChromeDevTools.Protocol.Chrome.Debugger.SetAsyncCallStackDepthCommand { MaxDepth = 32 }); await chromeSession.SendAsync(new MasterDevs.ChromeDevTools.Protocol.Chrome.DOM.SetNodeStackTracesEnabledCommand { Enable = true, }); await chromeSession.SendAsync(new MasterDevs.ChromeDevTools.Protocol.Chrome.Overlay.EnableCommand()); await chromeSession.SendAsync(new MasterDevs.ChromeDevTools.Protocol.Chrome.Overlay.SetShowViewportSizeOnResizeCommand { Show = true }); return(chromeSession); }
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 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)
} // 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(); }