Best Puppeteer-sharp code snippet using PuppeteerSharp.Payload.string
PuppeteerBrowser.cs
Source:PuppeteerBrowser.cs
...32 var options = new LaunchOptions33 {34 Headless = _Option.Headless,35 //UserDataDir = _Option.UserData,36 Args = new string[]37 {38 $"--user-data-dir=\"{ _Option.UserData}\"",39 //$"--profile-directory=\"{_Option.Profile}\"",40 $"--disable-extensions-except=\"{_Option.MetaMaskExtension}\"",41 $"--load-extension=\"{_Option.MetaMaskExtension}\"",42 "--disable-features=\"site-per-process\""43 },44 ExecutablePath = _Option.ChromePath,45 };46 config?.Invoke(options);47 _Browser = await Puppeteer.LaunchAsync(options);48 return _Browser;49 }50 public async Task<Page> GetMetaMashPageAsync(string HtmlName, int delayMsec = 2000, int timeOutMsec = 30000)51 {52 var current = DateTime.Now;53 while (true)54 {55 var lstTarget = _Browser.Targets();56 var lstTemp = lstTarget.Where(x => x.Url.Contains($"chrome-extension://{_Option.MetaMaskExtensionId}"));57 var target = lstTemp.FirstOrDefault(x => x.Url.ToLower().Contains(HtmlName.ToLower()));58 target = lstTemp.FirstOrDefault(x => x.Url.ToLower().Contains(HtmlName.ToLower()));59 if (target != null) return await target.PageAsync();60 await Task.Delay(delayMsec);61 if ((DateTime.Now - current).TotalMilliseconds > timeOutMsec)62 {63 return null;64 }65 }66 }67 public async Task ComfirmMetaMashAsync()68 {69 await GotoNavigateMetaMashAsync();70 ElementHandle buttonConfirm = null;71 int time = 0;72 while (buttonConfirm == null && ++time < 4)73 {74 var lstTemp = await MetaMaskPage.QuerySelectorAllAsync("button");75 var regexbtn = new Regex(@"^\s*Confirm\s*$", RegexOptions.IgnoreCase);76 foreach (var item in lstTemp)77 {78 var content = await MetaMaskPage.EvaluateFunctionAsync<string>("e => e.textContent", item);79 if (regexbtn.IsMatch(content))80 {81 buttonConfirm = item;82 break;83 }84 }85 await Task.Delay(3000);86 }87 if (buttonConfirm != null)88 {89 await buttonConfirm?.ClickAsync();90 }91 }92 public Page MetaMaskPage { get; set; }93 public async Task<bool> LoginAsync(string PassWord)94 {95 var pages = await _Browser.PagesAsync();96 RootPage = pages[0];97 await Task.Delay(5000);98 MetaMaskPage = await _Browser.NewPageAsync();99 await MetaMaskPage.BringToFrontAsync();100 await MetaMaskPage.GoToAsync(string.Format("chrome-extension://{0}/home.html#unlock", _Option.MetaMaskExtensionId));101 var pwd = await MetaMaskPage.WaitForSelectorAsync("*[type='password']");102 await pwd.TypeAsync(PassWord, new PuppeteerSharp.Input.TypeOptions { Delay = 100 });103 await Task.Delay(1000);104 var button = await MetaMaskPage.QuerySelectorAsync("button");105 await button.ClickAsync();106 var resCheck = MetaMaskPage.WaitForSelectorAsync("*[class='selected-account__clickable']");107 return resCheck != null;108 }109 public string _UrlGameApp = "https://dragonwars.game/#/train";110 public string _UrlMetaMashPopup { get => string.Format("chrome-extension://{0}/popup.html", _Option.MetaMaskExtensionId); }111 public string _UrlMetaMashHome { get => string.Format("chrome-extension://{0}/home.html#unlock", _Option.MetaMaskExtensionId); }112 public async Task InitialTabAsync()113 {114 var pages = await _Browser.PagesAsync();115 RootPage = pages[0];116 MetaMaskPage = await _Browser.NewPageAsync();117 }118 //public async Task<ElementHandle[]> GetHanleNavigateButtonsAsync()119 //{120 // await RootPage.WaitForSelectorAsync("ul.pagination li a");121 // return await RootPage.QuerySelectorAllAsync("ul.pagination li a");122 //}123 //public async Task<ElementHandle> GetHandleNavigateButtonAsync(string page)124 //{125 // var lstBtn = await GetHanleNavigateButtonsAsync();126 // return lstBtn.First(x => x.GetPropertyAsync("innerText").Result.JsonValueAsync().ToString().Equals(page));127 //}128 public async Task GotoNavigatePageAsync(int page)129 {130 await RootPage.BringToFrontAsync();131 await RootPage.GoToAsync($"https://dragonwars.game/#/train?page={page}");132 await Task.Delay(2000);133 }134 public async Task GotoNavigateMetaMashAsync()135 {136 await MetaMaskPage.BringToFrontAsync();137 await MetaMaskPage.GoToAsync(_UrlMetaMashPopup);138 await Task.Delay(2000);139 }140 public async Task<IList<PayloadDragonPage>> GetPageInfosAsync(MyPageDragonDTO myPageDragonDTO)141 {142 var lstData = new List<PayloadDragonPage>();143 for (int i = 1; i <= myPageDragonDTO.Payload.TotalPage; i++)144 {145 var client = new RestClient($"https://devabcde-api.dragonwars.game/v1/dragons/my-dragon?page={i}&rowPerPage=12&type=DRAGON");146 var request = new RestRequest();147 request.Method = Method.Get;148 request.AddHeader("wallet", _Option.Wallet);149 var response = await client.ExecuteAsync<MyPageDragonDTO>(request);150 lstData.Add(response.Data.Payload);151 }152 return lstData;153 }154 public async Task<IList<CardInfo>> GetCardItemsAsync(int page)155 {156 await Task.Delay(2000);157 await GotoNavigatePageAsync(page);158 var lstData = new List<CardInfo>();159 var lstTemp = await RootPage.QuerySelectorAllAsync(".grid > div.relative");160 var regexSpan = new Regex(@"^\s*#\d+\s*$");161 var regexbtn = new Regex(@"^\s*Adventure\s*$", RegexOptions.IgnoreCase);162 foreach (var item in lstTemp)163 {164 var spans = await item.QuerySelectorAllAsync("span");165 var card = new CardInfo();166 foreach (var span in spans)167 {168 var content = await span.EvaluateFunctionAsync<string>("e => e.textContent", item);169 if (regexSpan.IsMatch(content))170 {171 card.Id = content;172 break;173 }174 }175 //var buttons = await item.QuerySelectorAllAsync("button");176 //foreach (var button in buttons)177 //{178 // var content = await button.EvaluateFunctionAsync<string>("e => e.textContent", item);179 // if (regexbtn.IsMatch(content))180 // {181 // await item.ClickAsync();182 // card.AdventureButton = item;183 // break;184 // }185 //}186 lstData.Add(card);187 }188 return lstData;189 }190 public IList<HashSet<string>> GetAdventureForPage(AppInfo appInfo)191 {192 return appInfo.PayloadDragonPages.Select(x =>193 {194 var temp = (from d in x.Data195 join a in appInfo.AdventureInfo.Payload196 on d.Id equals a197 select $"#{a}");198 return temp.ToHashSet();199 }).ToList();200 }201 public async Task AdventureClickAsync(int index)202 {203 await RootPage.BringToFrontAsync();204 await RootPage.ClickAsync($".grid > div.relative:nth-child({index + 1}) button:nth-child(2)");...
AXNode.cs
Source:AXNode.cs
...10 {11 internal AccessibilityGetFullAXTreeResponse.AXTreeNode Payload { get; }12 public List<AXNode> Children { get; }13 public bool Focusable { get; set; }14 private readonly string _name;15 private string _role;16 private readonly bool _richlyEditable;17 private readonly bool _editable;18 private readonly bool _expanded;19 private readonly bool _hidden;20 private bool? _cachedHasFocusableChild;21 public AXNode(AccessibilityGetFullAXTreeResponse.AXTreeNode payload)22 {23 Payload = payload;24 Children = new List<AXNode>();25 _name = payload.Name != null ? payload.Name.Value.ToObject<string>() : string.Empty;26 _role = payload.Role != null ? payload.Role.Value.ToObject<string>() : "Unknown";27 _richlyEditable = payload.Properties.FirstOrDefault(p => p.Name == "editable")?.Value.Value.ToObject<string>() == "richtext";28 _editable |= _richlyEditable;29 _expanded = payload.Properties.FirstOrDefault(p => p.Name == "expanded")?.Value.Value.ToObject<bool>() == true;30 _hidden = payload.Properties.FirstOrDefault(p => p.Name == "hidden")?.Value.Value.ToObject<bool>() == true;31 Focusable = payload.Properties.FirstOrDefault(p => p.Name == "focusable")?.Value.Value.ToObject<bool>() == true;32 }33 internal static AXNode CreateTree(IEnumerable<AccessibilityGetFullAXTreeResponse.AXTreeNode> payloads)34 {35 var nodeById = new Dictionary<string, AXNode>();36 foreach (var payload in payloads)37 {38 nodeById[payload.NodeId] = new AXNode(payload);39 }40 foreach (var node in nodeById.Values)41 {42 foreach (var childId in node.Payload.ChildIds)43 {44 node.Children.Add(nodeById[childId]);45 }46 }47 return nodeById.Values.FirstOrDefault();48 }49 private bool IsPlainTextField()50 => !_richlyEditable && (_editable || _role == "textbox" || _role == "ComboBox" || _role == "searchbox");51 private bool IsTextOnlyObject()52 => _role == "LineBreak" ||53 _role == "text" ||54 _role == "InlineTextBox";55 private bool HasFocusableChild()56 {57 if (!_cachedHasFocusableChild.HasValue)58 {59 _cachedHasFocusableChild = Children.Any(c => c.Focusable || c.HasFocusableChild());60 }61 return _cachedHasFocusableChild.Value;62 }63 internal AXNode Find(Func<AXNode, bool> predicate)64 {65 if (predicate(this))66 {67 return this;68 }69 foreach (var child in Children)70 {71 var result = child.Find(predicate);72 if (result != null)73 {74 return result;75 }76 }77 return null;78 }79 internal bool IsLeafNode()80 {81 if (Children.Count == 0)82 {83 return true;84 }85 // These types of objects may have children that we use as internal86 // implementation details, but we want to expose them as leaves to platform87 // accessibility APIs because screen readers might be confused if they find88 // any children.89 if (IsPlainTextField() || IsTextOnlyObject())90 {91 return true;92 }93 // Roles whose children are only presentational according to the ARIA and94 // HTML5 Specs should be hidden from screen readers.95 // (Note that whilst ARIA buttons can have only presentational children, HTML596 // buttons are allowed to have content.)97 switch (_role)98 {99 case "doc-cover":100 case "graphics-symbol":101 case "img":102 case "Meter":103 case "scrollbar":104 case "slider":105 case "separator":106 case "progressbar":107 return true;108 }109 // Here and below: Android heuristics110 if (HasFocusableChild())111 {112 return false;113 }114 if (Focusable && !string.IsNullOrEmpty(_name))115 {116 return true;117 }118 if (_role == "heading" && !string.IsNullOrEmpty(_name))119 {120 return true;121 }122 return false;123 }124 internal bool IsControl()125 {126 switch (_role)127 {128 case "button":129 case "checkbox":130 case "ColorWell":131 case "combobox":132 case "DisclosureTriangle":133 case "listbox":134 case "menu":135 case "menubar":136 case "menuitem":137 case "menuitemcheckbox":138 case "menuitemradio":139 case "radio":140 case "scrollbar":141 case "searchbox":142 case "slider":143 case "spinbutton":144 case "switch":145 case "tab":146 case "textbox":147 case "tree":148 return true;149 default:150 return false;151 }152 }153 internal bool IsInteresting(bool insideControl)154 {155 if (_role == "Ignored" || _hidden)156 {157 return false;158 }159 if (Focusable || _richlyEditable)160 {161 return true;162 }163 // If it's not focusable but has a control role, then it's interesting.164 if (IsControl())165 {166 return true;167 }168 // A non focusable child of a control is not interesting169 if (insideControl)170 {171 return false;172 }173 return IsLeafNode() && !string.IsNullOrEmpty(_name);174 }175 internal SerializedAXNode Serialize()176 {177 var properties = new Dictionary<string, JToken>();178 foreach (var property in Payload.Properties)179 {180 properties[property.Name.ToLower()] = property.Value.Value;181 }182 if (Payload.Name != null)183 {184 properties["name"] = Payload.Name.Value;185 }186 if (Payload.Value != null)187 {188 properties["value"] = Payload.Value.Value;189 }190 if (Payload.Description != null)191 {192 properties["description"] = Payload.Description.Value;193 }194 var node = new SerializedAXNode195 {196 Role = _role,197 Name = properties.GetValueOrDefault("name")?.ToObject<string>(),198 Value = properties.GetValueOrDefault("value")?.ToObject<string>(),199 Description = properties.GetValueOrDefault("description")?.ToObject<string>(),200 KeyShortcuts = properties.GetValueOrDefault("keyshortcuts")?.ToObject<string>(),201 RoleDescription = properties.GetValueOrDefault("roledescription")?.ToObject<string>(),202 ValueText = properties.GetValueOrDefault("valuetext")?.ToObject<string>(),203 Disabled = properties.GetValueOrDefault("disabled")?.ToObject<bool>() ?? false,204 Expanded = properties.GetValueOrDefault("expanded")?.ToObject<bool>() ?? false,205 // WebArea"s treat focus differently than other nodes. They report whether their frame has focus,206 // not whether focus is specifically on the root node.207 Focused = properties.GetValueOrDefault("focused")?.ToObject<bool>() == true && _role != "WebArea",208 Modal = properties.GetValueOrDefault("modal")?.ToObject<bool>() ?? false,209 Multiline = properties.GetValueOrDefault("multiline")?.ToObject<bool>() ?? false,210 Multiselectable = properties.GetValueOrDefault("multiselectable")?.ToObject<bool>() ?? false,211 Readonly = properties.GetValueOrDefault("readonly")?.ToObject<bool>() ?? false,212 Required = properties.GetValueOrDefault("required")?.ToObject<bool>() ?? false,213 Selected = properties.GetValueOrDefault("selected")?.ToObject<bool>() ?? false,214 Checked = GetCheckedState(properties.GetValueOrDefault("checked")?.ToObject<string>()),215 Pressed = GetCheckedState(properties.GetValueOrDefault("pressed")?.ToObject<string>()),216 Level = properties.GetValueOrDefault("level")?.ToObject<int>() ?? 0,217 ValueMax = properties.GetValueOrDefault("valuemax")?.ToObject<int>() ?? 0,218 ValueMin = properties.GetValueOrDefault("valuemin")?.ToObject<int>() ?? 0,219 AutoComplete = GetIfNotFalse(properties.GetValueOrDefault("autocomplete")?.ToObject<string>()),220 HasPopup = GetIfNotFalse(properties.GetValueOrDefault("haspopup")?.ToObject<string>()),221 Invalid = GetIfNotFalse(properties.GetValueOrDefault("invalid")?.ToObject<string>()),222 Orientation = GetIfNotFalse(properties.GetValueOrDefault("orientation")?.ToObject<string>())223 };224 return node;225 }226 private string GetIfNotFalse(string value) => value != null && value != "false" ? value : null;227 private CheckedState GetCheckedState(string value)228 {229 switch (value)230 {231 case "mixed":232 return CheckedState.Mixed;233 case "true":234 return CheckedState.True;235 default:236 return CheckedState.False;237 }238 }239 }240}...
Program.cs
Source:Program.cs
...11namespace PuppeteerSharp.DevicesFetcher12{13 class Program14 {15 const string DEVICES_URL = "https://raw.githubusercontent.com/ChromeDevTools/devtools-frontend/master/front_end/emulated_devices/module.json";16 static string deviceDescriptorsOutput = "../../../../PuppeteerSharp/Mobile/DeviceDescriptors.cs";17 static string deviceDescriptorNameOutput = "../../../../PuppeteerSharp/Mobile/DeviceDescriptorName.cs";18 static async Task Main(string[] args)19 {20 var url = DEVICES_URL;21 if (args.Length > 0)22 {23 url = args[0];24 }25 string chromeVersion = null;26 var fetcher = new BrowserFetcher();27 await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);28 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions()))29 {30 chromeVersion = (await browser.GetVersionAsync()).Split('/').Last();31 }32 Console.WriteLine($"GET {url}");33 var text = await HttpGET(url);34 RootObject json = null;35 try36 {37 json = JsonConvert.DeserializeObject<RootObject>(text);38 }39 catch (Exception ex)40 {41 Console.WriteLine($"FAILED: error parsing response - {ex.Message}");42 }43 var devicePayloads = json.Extensions44 .Where(extension => extension.Type == "emulated-device")45 .Select(extension => extension.Device)46 .ToArray();47 var devices = new List<OutputDevice>();48 foreach (var payload in devicePayloads)49 {50 string[] names;51 if (payload.Title == "iPhone 6/7/8")52 {53 names = new[] { "iPhone 6", "iPhone 7", "iPhone 8" };54 }55 else if (payload.Title == "iPhone 6/7/8 Plus")56 {57 names = new[] { "iPhone 6 Plus", "iPhone 7 Plus", "iPhone 8 Plus" };58 }59 else if (payload.Title == "iPhone 5/SE")60 {61 names = new[] { "iPhone 5", "iPhone SE" };62 }63 else64 {65 names = new[] { payload.Title };66 }67 foreach (var name in names)68 {69 var device = CreateDevice(chromeVersion, name, payload, false);70 var landscape = CreateDevice(chromeVersion, name, payload, true);71 devices.Add(device);72 if (landscape.Viewport.Width != device.Viewport.Width || landscape.Viewport.Height != device.Viewport.Height)73 {74 devices.Add(landscape);75 }76 }77 }78 devices.RemoveAll(device => !device.Viewport.IsMobile);79 devices.Sort((a, b) => a.Name.CompareTo(b.Name));80 WriteDeviceDescriptors(devices);81 WriteDeviceDescriptorName(devices);82 }83 static void WriteDeviceDescriptors(IEnumerable<OutputDevice> devices)84 {85 var builder = new StringBuilder();86 var begin = @"using System.Collections.Generic;87namespace PuppeteerSharp.Mobile88{89 /// <summary>90 /// Device descriptors.91 /// </summary>92 public class DeviceDescriptors93 {94 private static readonly Dictionary<DeviceDescriptorName, DeviceDescriptor> Devices = new Dictionary<DeviceDescriptorName, DeviceDescriptor>95 {96";97 var end = @"98 };99 100 /// <summary>101 /// Get the specified device description.102 /// </summary>103 /// <returns>The device descriptor.</returns>104 /// <param name=""name"">Device Name.</param>105 public static DeviceDescriptor Get(DeviceDescriptorName name) => Devices[name];106 }107}";108 builder.Append(begin);109 builder.AppendJoin(",\n", devices.Select(GenerateCsharpFromDevice));110 builder.Append(end);111 File.WriteAllText(deviceDescriptorsOutput, builder.ToString());112 }113 static void WriteDeviceDescriptorName(IEnumerable<OutputDevice> devices)114 {115 var builder = new StringBuilder();116 var begin = @"namespace PuppeteerSharp.Mobile117{118 /// <summary>119 /// Device descriptor name.120 /// </summary>121 public enum DeviceDescriptorName122 {";123 var end = @"124 }125}";126 builder.Append(begin);127 builder.AppendJoin(",", devices.Select(device =>128 {129 return $@"130 /// <summary>131 /// {device.Name}132 /// </summary>133 {DeviceNameToEnumValue(device)}";134 }));135 builder.Append(end);136 File.WriteAllText(deviceDescriptorNameOutput, builder.ToString());137 }138 static string GenerateCsharpFromDevice(OutputDevice device)139 {140 var w = string.Empty;141 return $@" [DeviceDescriptorName.{DeviceNameToEnumValue(device)}] = new DeviceDescriptor142 {{143 Name = ""{device.Name}"",144 UserAgent = ""{device.UserAgent}"",145 ViewPort = new ViewPortOptions146 {{147 Width = {device.Viewport.Width},148 Height = {device.Viewport.Height},149 DeviceScaleFactor = {device.Viewport.DeviceScaleFactor},150 IsMobile = {device.Viewport.IsMobile.ToString().ToLower()},151 HasTouch = {device.Viewport.HasTouch.ToString().ToLower()},152 IsLandscape = {device.Viewport.IsLandscape.ToString().ToLower()}153 }}154 }}";155 }156 static string DeviceNameToEnumValue(OutputDevice device)157 {158 var output = new StringBuilder();159 output.Append(char.ToUpper(device.Name[0]));160 for (var i = 1; i < device.Name.Length; i++)161 {162 if (char.IsWhiteSpace(device.Name[i]))163 {164 output.Append(char.ToUpper(device.Name[i + 1]));165 i++;166 }167 else168 {169 output.Append(device.Name[i]);170 }171 }172 return output.ToString();173 }174 static OutputDevice CreateDevice(string chromeVersion, string deviceName, RootObject.Device descriptor, bool landscape)175 {176 var devicePayload = LoadFromJSONV1(descriptor);177 var viewportPayload = landscape ? devicePayload.Horizontal : devicePayload.Vertical;178 return new OutputDevice179 {180 Name = deviceName + (landscape ? " landscape" : string.Empty),181 UserAgent = devicePayload.UserAgent.Replace("%s", chromeVersion),182 Viewport = new OutputDevice.OutputDeviceViewport183 {184 Width = viewportPayload.Width,185 Height = viewportPayload.Height,186 DeviceScaleFactor = devicePayload.DeviceScaleFactor,187 IsMobile = devicePayload.Capabilities.Contains("mobile"),188 HasTouch = devicePayload.Capabilities.Contains("touch"),189 IsLandscape = landscape190 }191 };192 }193 static DevicePayload LoadFromJSONV1(RootObject.Device json) => new DevicePayload194 {195 Type = json.Type,196 UserAgent = json.UserAgent,197 Capabilities = json.Capabilities.ToHashSet(),198 DeviceScaleFactor = json.Screen.DevicePixelRatio,199 Horizontal = new ViewportPayload200 {201 Height = json.Screen.Horizontal.Height,202 Width = json.Screen.Horizontal.Width203 },204 Vertical = new ViewportPayload205 {206 Height = json.Screen.Vertical.Height,207 Width = json.Screen.Vertical.Width208 }209 };210 static Task<string> HttpGET(string url) => new HttpClient().GetStringAsync(url);211 }212}...
FrameManager.cs
Source:FrameManager.cs
...16 internal FrameManager(CDPSession client, FrameTree frameTree, Page page)17 {18 _client = client;19 _page = page;20 Frames = new Dictionary<string, Frame>();21 _contextIdToContext = new Dictionary<int, ExecutionContext>();22 _logger = _client.Connection.LoggerFactory.CreateLogger<FrameManager>();23 _client.MessageReceived += _client_MessageReceived;24 HandleFrameTree(frameTree);25 }26 #region Properties27 internal event EventHandler<FrameEventArgs> FrameAttached;28 internal event EventHandler<FrameEventArgs> FrameDetached;29 internal event EventHandler<FrameEventArgs> FrameNavigated;30 internal event EventHandler<FrameEventArgs> LifecycleEvent;31 internal Dictionary<string, Frame> Frames { get; set; }32 internal Frame MainFrame { get; set; }33 #endregion34 #region Private Methods35 void _client_MessageReceived(object sender, PuppeteerSharp.MessageEventArgs e)36 {37 switch (e.MessageID)38 {39 case "Page.frameAttached":40 OnFrameAttached(e.MessageData.frameId.ToString(), e.MessageData.parentFrameId.ToString());41 break;42 case "Page.frameNavigated":43 OnFrameNavigated(((JObject)e.MessageData.frame).ToObject<FramePayload>());44 break;45 case "Page.frameDetached":46 OnFrameDetached(e.MessageData.frameId.ToString());47 break;48 case "Runtime.executionContextCreated":49 OnExecutionContextCreated(new ContextPayload(e.MessageData.context));50 break;51 case "Runtime.executionContextDestroyed":52 OnExecutionContextDestroyed((int)e.MessageData.executionContextId);53 break;54 case "Runtime.executionContextsCleared":55 OnExecutionContextsCleared();56 break;57 case "Page.lifecycleEvent":58 OnLifeCycleEvent(e);59 break;60 default:61 break;62 }63 }64 private void OnLifeCycleEvent(MessageEventArgs e)65 {66 if (Frames.ContainsKey(e.MessageData.frameId.ToString()))67 {68 Frame frame = Frames[e.MessageData.frameId.ToString()];69 frame.OnLifecycleEvent(e.MessageData.loaderId.ToString(), e.MessageData.name.ToString());70 LifecycleEvent?.Invoke(this, new FrameEventArgs(frame));71 }72 }73 private void OnExecutionContextsCleared()74 {75 foreach (var context in _contextIdToContext.Values)76 {77 RemoveContext(context);78 }79 _contextIdToContext.Clear();80 }81 private void OnExecutionContextDestroyed(int executionContextId)82 {83 _contextIdToContext.TryGetValue(executionContextId, out var context);84 if (context != null)85 {86 _contextIdToContext.Remove(executionContextId);87 RemoveContext(context);88 }89 }90 public JSHandle CreateJsHandle(int contextId, dynamic remoteObject)91 {92 _contextIdToContext.TryGetValue(contextId, out var storedContext);93 if (storedContext == null)94 {95 _logger.LogError("INTERNAL ERROR: missing context with id = {ContextId}", contextId);96 }97 if (remoteObject.subtype == "node")98 {99 return new ElementHandle(storedContext, _client, remoteObject, _page);100 }101 return new JSHandle(storedContext, _client, remoteObject);102 }103 private void OnExecutionContextCreated(ContextPayload contextPayload)104 {105 var context = new ExecutionContext(_client, contextPayload,106 remoteObject => CreateJsHandle(contextPayload.Id, remoteObject));107 _contextIdToContext[contextPayload.Id] = context;108 var frame = !string.IsNullOrEmpty(context.FrameId) ? Frames[context.FrameId] : null;109 if (frame != null && context.IsDefault)110 {111 frame.SetDefaultContext(context);112 }113 }114 private void OnFrameDetached(string frameId)115 {116 if (Frames.ContainsKey(frameId))117 {118 RemoveFramesRecursively(Frames[frameId]);119 }120 }121 private void OnFrameNavigated(FramePayload framePayload)122 {123 var isMainFrame = string.IsNullOrEmpty(framePayload.ParentId);124 var frame = isMainFrame ? MainFrame : Frames[framePayload.Id];125 Contract.Assert(isMainFrame || frame != null, "We either navigate top level or have old version of the navigated frame");126 // Detach all child frames first.127 if (frame != null)128 {129 while (frame.ChildFrames.Count > 0)130 {131 RemoveFramesRecursively(frame.ChildFrames[0]);132 }133 }134 // Update or create main frame.135 if (isMainFrame)136 {137 if (frame != null)138 {139 // Update frame id to retain frame identity on cross-process navigation.140 if (frame.Id != null)141 {142 Frames.Remove(frame.Id);143 }144 frame.Id = framePayload.Id;145 }146 else147 {148 // Initial main frame navigation.149 frame = new Frame(this._client, this._page, null, framePayload.Id);150 }151 Frames[framePayload.Id] = frame;152 MainFrame = frame;153 }154 // Update frame payload.155 frame.Navigated(framePayload);156 FrameNavigated?.Invoke(this, new FrameEventArgs(frame));157 }158 private void RemoveContext(ExecutionContext context)159 {160 var frame = !string.IsNullOrEmpty(context.FrameId) ? Frames[context.FrameId] : null;161 if (frame != null && context.IsDefault)162 {163 frame.SetDefaultContext(null);164 }165 }166 private void RemoveFramesRecursively(Frame frame)167 {168 while (frame.ChildFrames.Count > 0)169 {170 RemoveFramesRecursively(frame.ChildFrames[0]);171 }172 frame.Detach();173 Frames.Remove(frame.Id);174 FrameDetached?.Invoke(this, new FrameEventArgs(frame));175 }176 private void OnFrameAttached(string frameId, string parentFrameId)177 {178 if (!Frames.ContainsKey(frameId) && Frames.ContainsKey(parentFrameId))179 {180 var parentFrame = Frames[parentFrameId];181 var frame = new Frame(_client, _page, parentFrame, frameId);182 Frames[frame.Id] = frame;183 FrameAttached?.Invoke(this, new FrameEventArgs(frame));184 }185 }186 private void HandleFrameTree(FrameTree frameTree)187 {188 if (!string.IsNullOrEmpty(frameTree.Frame.ParentId))189 {190 OnFrameAttached(frameTree.Frame.Id, frameTree.Frame.ParentId);191 }192 OnFrameNavigated(frameTree.Frame);193 if (frameTree.Childs != null)194 {195 foreach (var child in frameTree.Childs)196 {197 HandleFrameTree(child);198 }199 }200 }201 #endregion202 }...
CaptureService.cs
Source:CaptureService.cs
...26 public async override Task<CaptureReply> Perform(CaptureRequest request, ServerCallContext context)27 {28 var url = request.Url;29 var imageUrl = "/images/background.jpg";30 if(request.ImageBytes != null && !string.IsNullOrEmpty(request.ImageName )) 31 {32 imageUrl = await _storageService.SaveDocument(request.ImageName, request.ImageType, request.ImageBytes.ToArray());33 }34 var keyValuePairs = new NameValueCollection();35 keyValuePairs.Add("imageUrl", imageUrl);36 keyValuePairs.Add("message", request.Message); 37 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);38 var options = new LaunchOptions39 {40 Headless = true41 };42 using (var browser = await Puppeteer.LaunchAsync(options))43 using(var page = await browser.NewPageAsync()) 44 {45 await page.SetRequestInterceptionAsync(true);46 page.Request += async (sender, e) =>47 {48 if(e.Request.Url != url) 49 {50 await e.Request.ContinueAsync();51 return;52 }53 //54 var payload = new Payload()55 {56 Headers = new Dictionary<string, string>{{"Content-Type", "application/x-www-form-urlencoded"}},57 Url = url,58 Method = HttpMethod.Post,59 PostData = String.Join("&",60 keyValuePairs.AllKeys.Select(a => a + "=" + HttpUtility.UrlEncode(keyValuePairs[a])))61 };62 await e.Request.ContinueAsync(payload);63 await Console.Out.WriteLineAsync($"REQUEST: {e.Request.Method} {e.Request.Url} {payload.PostData}");64 };65 page.Response += async (sender, e) =>66 {67 await Console.Out.WriteLineAsync($"RESPONSE: {e.Response.Url} -({e.Response.Request.Method}) {e.Response.Status:d} {e.Response.StatusText}");68 };69 await page.GoToAsync(url, WaitUntilNavigation.Networkidle0);70 var htmlData = await page.GetContentAsync();...
Payload.cs
Source:Payload.cs
...13 public class Payload14 {15 internal Payload()16 {17 Headers = new Dictionary<string, object>();18 }1920 /// <summary>21 /// Gets or sets the HTTP method.22 /// </summary>23 /// <value>HTTP method.</value>24 [JsonProperty("method"), JsonConverter(typeof(HttpMethodConverter))]25 public HttpMethod Method { get; internal set; }26 /// <summary>27 /// Gets or sets the post data.28 /// </summary>29 /// <value>The post data.</value>30 [JsonProperty("postData")]31 public object PostData { get; internal set; }32 /// <summary>33 /// Gets or sets the HTTP headers.34 /// </summary>35 /// <value>HTTP headers.</value>36 [JsonProperty("headers")]37 public Dictionary<string, object> Headers { get; internal set; }38 /// <summary>39 /// Gets or sets the URL.40 /// </summary>41 /// <value>The URL.</value>42 [JsonProperty("url")]43 public string Url { get; internal set; }44 [JsonIgnore]45 internal string Hash46 {47 get48 {49 var normalizedUrl = Url;50 try51 {52 // Decoding is necessary to normalize URLs.53 // The method will throw if the URL is malformed. In this case,54 // consider URL to be normalized as-is.55 normalizedUrl = HttpUtility.UrlDecode(Url);56 }57 catch58 {59 }...
FrameTree.cs
Source:FrameTree.cs
1using System.Collections.Generic;2using Newtonsoft.Json.Linq;3using PuppeteerSharp.Helpers;4using PuppeteerSharp.Messaging;5namespace PuppeteerSharp6{7 internal class FrameTree8 {9 internal FrameTree()10 {11 Childs = new List<FrameTree>();12 }13 internal FrameTree(JToken frameTree)14 {15 var frame = frameTree[MessageKeys.Frame];16 Frame = new FramePayload17 {18 Id = frame[MessageKeys.Id].AsString(),19 ParentId = frame[MessageKeys.ParentId].AsString(),20 Name = frame[MessageKeys.Name].AsString(),21 Url = frame[MessageKeys.Url].AsString()22 };23 Childs = new List<FrameTree>();24 LoadChilds(this, frameTree);25 }26 #region Properties27 internal FramePayload Frame { get; set; }28 internal List<FrameTree> Childs { get; set; }29 #endregion30 #region Private Functions31 private void LoadChilds(FrameTree frame, JToken frameTree)32 {33 var childFrames = frameTree[MessageKeys.ChildFrames];34 if (childFrames != null)35 {36 foreach (var item in childFrames)37 {38 var childFrame = item[MessageKeys.Frame];39 var newFrame = new FrameTree40 {41 Frame = new FramePayload42 {43 Id = childFrame[MessageKeys.Id].AsString(),44 ParentId = childFrame[MessageKeys.ParentId].AsString(),45 Url = childFrame[MessageKeys.Url].AsString()46 }47 };48 if ((item as JObject)[MessageKeys.ChildFrames] != null)49 {50 LoadChilds(newFrame, item);51 }52 frame.Childs.Add(newFrame);53 }54 }55 }56 #endregion57 }58}...
BindingCalledResponse.cs
Source:BindingCalledResponse.cs
...4namespace PuppeteerSharp.Messaging5{6 internal class BindingCalledResponse7 {8 private string _payloadJson;9 public int ExecutionContextId { get; set; }10 public BindingCalledResponsePayload BindingPayload { get; set; }11 public string Payload12 {13 get => _payloadJson;14 set15 {16 _payloadJson = value;17 var json = JsonConvert.DeserializeObject(_payloadJson, JsonHelper.DefaultJsonSerializerSettings) as JObject;18 BindingPayload = json.ToObject<BindingCalledResponsePayload>(true);19 BindingPayload.JsonObject = json;20 }21 }22 internal class BindingCalledResponsePayload23 {24 public string Name { get; set; }25 public JToken[] Args { get; set; }26 public int Seq { get; set; }27 public JObject JsonObject { get; set; }28 }29 }30}...
string
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 var response = await page.EvaluateFunctionAsync<string>("() => {return 'hello world';}");13 Console.WriteLine(response);14 await browser.CloseAsync();15 }16 }17}18using PuppeteerSharp;19using System;20using System.Threading.Tasks;21{22 {23 static async Task Main(string[] args)24 {25 var browser = await Puppeteer.LaunchAsync(new LaunchOptions26 {27 });28 var page = await browser.NewPageAsync();29 var response = await page.EvaluateFunctionAsync<int>("() => {return 10;}");30 Console.WriteLine(response);31 await browser.CloseAsync();32 }33 }34}35using PuppeteerSharp;36using System;37using System.Threading.Tasks;38{39 {40 static async Task Main(string[] args)41 {42 var browser = await Puppeteer.LaunchAsync(new LaunchOptions43 {44 });45 var page = await browser.NewPageAsync();
string
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync();9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });10 var page = await browser.NewPageAsync();11 await page.ScreenshotAsync("google.png");12 await browser.CloseAsync();13 }14 }15}16using PuppeteerSharp;17using System;18using System.Threading.Tasks;19{20 {21 static async Task Main(string[] args)22 {23 await new BrowserFetcher().DownloadAsync();24 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });25 var page = await browser.NewPageAsync();26 await page.ScreenshotAsync("google.png");27 await browser.CloseAsync();28 }29 }30}31using PuppeteerSharp;32using System;33using System.Threading.Tasks;34{35 {36 static async Task Main(string[] args)37 {38 await new BrowserFetcher().DownloadAsync();39 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });40 var page = await browser.NewPageAsync();41 await page.ScreenshotAsync("google.png");42 await browser.CloseAsync();43 }44 }45}46using PuppeteerSharp;47using System;48using System.Threading.Tasks;49{50 {51 static async Task Main(string[] args)52 {53 await new BrowserFetcher().DownloadAsync();54 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });55 var page = await browser.NewPageAsync();56 await page.ScreenshotAsync("google.png");57 await browser.CloseAsync();58 }59 }60}
string
Using AI Code Generation
1var puppeteer = require ( 'puppeteer' );2( async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({ path: 'example.png' });6 await page.pdf({ path: 'hn.pdf', format: 'A4' });7 await browser.close();8})();9var puppeteer = require ( 'puppeteer' );10( async () => {11 const browser = await puppeteer.launch();12 const page = await browser.newPage();13 await page.screenshot({ path: 'example.png' });14 await page.pdf({ path: 'hn.pdf', format: 'A4' });15 await browser.close();16})();17var puppeteer = require ( 'puppeteer' );18( async () => {19 const browser = await puppeteer.launch();20 const page = await browser.newPage();21 await page.screenshot({ path: 'example.png' });22 await page.pdf({ path: 'hn.pdf', format: 'A4' });23 await browser.close();24})();25var puppeteer = require ( 'puppeteer' );26( async () => {27 const browser = await puppeteer.launch();28 const page = await browser.newPage();29 await page.screenshot({ path: 'example.png' });30 await page.pdf({ path: 'hn.pdf', format: 'A4' });31 await browser.close();32})();33var puppeteer = require ( 'puppeteer' );
string
Using AI Code Generation
1var str = payload.ToString();2Console.WriteLine("Payload: " + str);3var json = payload.Json;4Console.WriteLine("Payload: " + json);5var data = payload.Data;6Console.WriteLine("Payload: " + data);7var text = payload.Text;8Console.WriteLine("Payload: " + text);9var jsonStr = payload.JsonString;10Console.WriteLine("Payload: " + jsonStr);11var jsonVal = payload.JsonValue;12Console.WriteLine("Payload: " + jsonVal);13var json = payload.Json;14Console.WriteLine("Payload: " + json);15var data = payload.Data;16Console.WriteLine("Payload: " + data);17var text = payload.Text;18Console.WriteLine("Payload: " + text);19var jsonStr = payload.JsonString;20Console.WriteLine("Payload: " + jsonStr);21var jsonVal = payload.JsonValue;22Console.WriteLine("Payload: " + jsonVal);23var json = payload.Json;24Console.WriteLine("Payload: " + json);25var data = payload.Data;26Console.WriteLine("Payload: " + data);27var text = payload.Text;28Console.WriteLine("Payload: " + text);29var jsonStr = payload.JsonString;30Console.WriteLine("Payload: " + jsonStr);31var jsonVal = payload.JsonValue;32Console.WriteLine("Payload: " + jsonVal);33var json = payload.Json;34Console.WriteLine("Payload: " + json);
string
Using AI Code Generation
1var payload = new Payload();2payload.Data = "Hello World";3await page.EvaluateExpressionAsync("console.log('" + payload.Data + "')");4var payload = new Payload();5payload.Data = "Hello World";6await page.EvaluateExpressionAsync($"console.log('{payload.Data}')");7var payload = new Payload();8payload.Data = "Hello World";9await page.EvaluateExpressionAsync("console.log('" + payload.Data + "')");10var payload = new Payload();11payload.Data = "Hello World";12await page.EvaluateExpressionAsync("console.log('" + payload.Data + "')");13var payload = new Payload();14payload.Data = "Hello World";15await page.EvaluateExpressionAsync($"console.log('{payload.Data}')");16var payload = new Payload();17payload.Data = "Hello World";18await page.EvaluateExpressionAsync("console.log('" + payload.Data + "')");19var payload = new Payload();20payload.Data = "Hello World";21await page.EvaluateExpressionAsync("console.log('" + payload.Data + "')");22var payload = new Payload();23payload.Data = "Hello World";24await page.EvaluateExpressionAsync($"console.log('{payload.Data}')");25var payload = new Payload();26payload.Data = "Hello World";27await page.EvaluateExpressionAsync("console.log('" + payload.Data + "')");28var payload = new Payload();29payload.Data = "Hello World";30await page.EvaluateExpressionAsync("console.log('" + payload.Data + "')");31var payload = new Payload();32payload.Data = "Hello World";33await page.EvaluateExpressionAsync($"console.log('{payload.Data}')");34var payload = new Payload();35payload.Data = "Hello World";36await page.EvaluateExpressionAsync("console.log('" + payload.Data + "')");37var payload = new Payload();38payload.Data = "Hello World";39await page.EvaluateExpressionAsync("console.log('" + payload.Data + "')");
string
Using AI Code Generation
1var payload = new Payload("2", "2.cs");2var payloadString = payload.ToString();3Console.WriteLine(payloadString);4var page = await browser.NewPageAsync();5var pageString = page.ToString();6Console.WriteLine(pageString);7var page = await browser.NewPageAsync();8var pageString = page.ToString();9Console.WriteLine(pageString);10var page = await browser.NewPageAsync();11var pageString = page.ToString();12Console.WriteLine(pageString);13var page = await browser.NewPageAsync();14var pageString = page.ToString();15Console.WriteLine(pageString);16var page = await browser.NewPageAsync();17var pageString = page.ToString();18Console.WriteLine(pageString);19var page = await browser.NewPageAsync();20var pageString = page.ToString();21Console.WriteLine(pageString);22var page = await browser.NewPageAsync();23var pageString = page.ToString();24Console.WriteLine(pageString);25var page = await browser.NewPageAsync();26var pageString = page.ToString();27Console.WriteLine(pageString);28var page = await browser.NewPageAsync();29var pageString = page.ToString();30Console.WriteLine(pageString);
string
Using AI Code Generation
1var data = payload.Data.ToString();2var data = payload.Data.ToString();3var data = payload.Data.ToString();4var data = payload.Data.ToString();5var data = payload.Data.ToString();6var data = payload.Data.ToString();7var data = payload.Data.ToString();8var data = payload.Data.ToString();9var data = payload.Data.ToString();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!