コード例 #1
0
        /// <inheritdoc cref="IBrowser.NewContextAsync"/>
        public async Task <IBrowserContext> NewContextAsync(BrowserContextOptions options = null)
        {
            string browserContextId = (await _session.SendAsync(new TargetCreateBrowserContextRequest()).ConfigureAwait(false)).BrowserContextId;
            var    context          = CreateBrowserContext(browserContextId, options);
            await context.InitializeAsync().ConfigureAwait(false);

            _contexts.Add(browserContextId, context);
            return(context);
        }
コード例 #2
0
        public async Task <T> EvaluateAsync <T>(ExecutionContext context, bool returnByValue, string script, object[] args)
        {
            string       suffix       = $"//# sourceURL={EvaluationScriptUrl}";
            RemoteObject remoteObject = null;

            if (script.IsJavascriptFunction())
            {
                RuntimeCallFunctionOnResponse result = null;

                try
                {
                    result = await _client.SendAsync(new RuntimeCallFunctionOnRequest
                    {
                        FunctionDeclaration = $"{script}\n{suffix}\n",
                        ExecutionContextId  = ContextId,
                        Arguments           = args.Select(a => FormatArgument(a, context)).ToArray(),
                        ReturnByValue       = returnByValue,
                        AwaitPromise        = true,
                        UserGesture         = true,
                    }).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    result = RewriteError(ex);
                }

                if (result.ExceptionDetails != null)
                {
                    throw new PlaywrightSharpException($"Evaluation failed: {result.ExceptionDetails.ToExceptionMessage()}");
                }

                remoteObject = result.Result;
            }
            else
            {
                string expressionWithSourceUrl = _sourceUrlRegex.IsMatch(script) ? script : script + '\n' + suffix;
                var    result = await _client.SendAsync(new RuntimeEvaluateRequest
                {
                    Expression    = expressionWithSourceUrl,
                    ContextId     = ContextId,
                    ReturnByValue = returnByValue,
                    AwaitPromise  = true,
                    UserGesture   = true,
                }).ConfigureAwait(false);

                if (result.ExceptionDetails != null)
                {
                    throw new PlaywrightSharpException($"Evaluation failed: {result.ExceptionDetails.ToExceptionMessage()}");
                }

                remoteObject = result.Result;
            }

            return((T)(returnByValue ? GetValueFromRemoteObject <T>(remoteObject) : context.CreateHandle(remoteObject)));
        }
コード例 #3
0
        internal Task StartAsync(CoverageStartOptions options)
        {
            if (_enabled)
            {
                throw new InvalidOperationException("JSCoverage is already enabled");
            }

            _resetOnNavigation      = options.ResetOnNavigation;
            _reportAnonymousScripts = options.ReportAnonymousScripts;
            _enabled = true;
            _scriptURLs.Clear();
            _scriptSources.Clear();

            _client.MessageReceived += Client_MessageReceived;

            return(Task.WhenAll(
                       _client.SendAsync(new ProfilerEnableRequest()),
                       _client.SendAsync(new ProfilerStartPreciseCoverageRequest
            {
                CallCount = false,
                Detailed = true,
            }),
                       _client.SendAsync(new DebuggerEnableRequest()),
                       _client.SendAsync(new DebuggerSetSkipAllPausesRequest
            {
                Skip = true,
            })));
        }
コード例 #4
0
 public async Task AbortAsync(RequestAbortErrorCode errorCode = RequestAbortErrorCode.Failed)
 {
     try
     {
         await _client.SendAsync(new FetchFailRequestRequest
         {
             RequestId   = InterceptionId,
             ErrorReason = errorCode.ToErrorReasonProtocol(),
         }).ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex);
     }
 }
コード例 #5
0
        /// <inheritdoc cref="IBrowser.StopTracingAsync"/>
        public async Task <string> StopTracingAsync()
        {
            var taskWrapper = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously);

            async void EventHandler(object sender, IChromiumEvent e)
            {
                try
                {
                    if (e is TracingTracingCompleteChromiumEvent tracingTracingComplete)
                    {
                        string stream      = tracingTracingComplete.Stream;
                        string tracingData = await ProtocolStreamReader.ReadProtocolStreamStringAsync(_tracingClient, stream, _tracingPath).ConfigureAwait(false);

                        _client.MessageReceived -= EventHandler;
                        taskWrapper.TrySetResult(tracingData);
                    }
                }
                catch (Exception ex)
                {
                    string message = $"Tracing failed to process the tracing complete. {ex.Message}. {ex.StackTrace}";
                    System.Diagnostics.Debug.WriteLine(ex);
                    _tracingClient.OnClosed(message);
                }
            }

            _tracingClient.MessageReceived += EventHandler;

            await _tracingClient.SendAsync(new TracingEndRequest()).ConfigureAwait(false);

            _tracingRecording = false;

            return(await taskWrapper.Task.ConfigureAwait(false));
        }
コード例 #6
0
        public async Task <IAXNode> FindElementAsync(ElementHandle element)
        {
            var remoteObject = element.RemoteObject;
            var result       = await _client.SendAsync(new DOMDescribeNodeRequest { ObjectId = remoteObject.ObjectId }).ConfigureAwait(false);

            var needle = Find(node => node.Payload.BackendDOMNodeId == result.Node.BackendNodeId);

            return(needle);
        }
コード例 #7
0
        internal static async Task <string> ReadProtocolStreamStringAsync(ChromiumSession client, string handle, string path)
        {
            var result = new StringBuilder();
            var fs     = !string.IsNullOrEmpty(path) ? AsyncFileHelper.CreateStream(path, FileMode.Create) : null;

            try
            {
                bool eof = false;

                while (!eof)
                {
                    var response = await client.SendAsync(new IOReadRequest
                    {
                        Handle = handle,
                    }).ConfigureAwait(false);

                    eof = response.Eof.Value;

                    result.Append(response.Data);

                    if (fs != null)
                    {
                        var data = Encoding.UTF8.GetBytes(response.Data);
                        await fs.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
                    }
                }

                await client.SendAsync(new IOCloseRequest
                {
                    Handle = handle,
                }).ConfigureAwait(false);

                return(result.ToString());
            }
            finally
            {
                fs?.Dispose();
            }
        }
コード例 #8
0
        internal static async Task <byte[]> ReadProtocolStreamByteAsync(ChromiumSession client, string handle, string path)
        {
            IEnumerable <byte> result = null;
            bool eof = false;
            var  fs  = !string.IsNullOrEmpty(path) ? AsyncFileHelper.CreateStream(path, FileMode.Create) : null;

            try
            {
                while (!eof)
                {
                    var response = await client.SendAsync(new IOReadRequest
                    {
                        Handle = handle,
                    }).ConfigureAwait(false);

                    eof = response.Eof.Value;
                    var data = Convert.FromBase64String(response.Data);
                    result = result == null ? data : result.Concat(data);

                    if (fs != null)
                    {
                        await fs.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
                    }
                }

                await client.SendAsync(new IOCloseRequest
                {
                    Handle = handle,
                }).ConfigureAwait(false);

                return(result.ToArray());
            }
            finally
            {
                fs?.Dispose();
            }
        }
コード例 #9
0
        public async Task <byte[]> GenerateAsync(string file, PdfOptions options)
        {
            double paperWidth  = PaperFormat.Letter.Width;
            double paperHeight = PaperFormat.Letter.Height;

            if (options.Format != null)
            {
                paperWidth  = options.Format.Width;
                paperHeight = options.Format.Height;
            }
            else
            {
                if (options.Width != null)
                {
                    paperWidth = ConvertPrintParameterToInches(options.Width);
                }

                if (options.Height != null)
                {
                    paperHeight = ConvertPrintParameterToInches(options.Height);
                }
            }

            double marginTop    = ConvertPrintParameterToInches(options.MarginOptions.Top);
            double marginLeft   = ConvertPrintParameterToInches(options.MarginOptions.Left);
            double marginBottom = ConvertPrintParameterToInches(options.MarginOptions.Bottom);
            double marginRight  = ConvertPrintParameterToInches(options.MarginOptions.Right);

            var result = await _client.SendAsync(new PagePrintToPDFRequest
            {
                TransferMode        = "ReturnAsStream",
                Landscape           = options.Landscape,
                DisplayHeaderFooter = options.DisplayHeaderFooter,
                HeaderTemplate      = options.HeaderTemplate,
                FooterTemplate      = options.FooterTemplate,
                PrintBackground     = options.PrintBackground,
                Scale             = options.Scale,
                PaperWidth        = paperWidth,
                PaperHeight       = paperHeight,
                MarginTop         = marginTop,
                MarginBottom      = marginBottom,
                MarginLeft        = marginLeft,
                MarginRight       = marginRight,
                PageRanges        = options.PageRanges,
                PreferCSSPageSize = options.PreferCSSPageSize,
            }).ConfigureAwait(false);

            return(await ProtocolStreamReader.ReadProtocolStreamByteAsync(_client, result.Stream, file).ConfigureAwait(false));
        }
コード例 #10
0
        internal static async Task ReleaseObjectAsync(ChromiumSession client, IRemoteObject remoteObject)
        {
            if (string.IsNullOrEmpty(remoteObject.ObjectId))
            {
                return;
            }

            try
            {
                await client.SendAsync(new RuntimeReleaseObjectRequest
                {
                    ObjectId = remoteObject.ObjectId,
                }).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
コード例 #11
0
        internal Task StartAsync(CoverageStartOptions options)
        {
            if (_enabled)
            {
                throw new InvalidOperationException("CSSCoverage is already enabled");
            }

            _resetOnNavigation = options.ResetOnNavigation;
            _enabled           = true;
            _stylesheetURLs.Clear();
            _stylesheetSources.Clear();

            _client.MessageReceived += Client_MessageReceived;

            return(Task.WhenAll(
                       _client.SendAsync(new DOMEnableRequest()),
                       _client.SendAsync(new CSSEnableRequest()),
                       _client.SendAsync(new CSSStartRuleUsageTrackingRequest())));
        }
コード例 #12
0
        /// <inheritdoc cref="IBrowserContextDelegate.NewPageAsync"/>
        public async Task <IPage> NewPageAsync()
        {
            var createTargetRequest = new TargetCreateTargetRequest
            {
                Url = "about:blank",
            };

            if (_contextId != null)
            {
                createTargetRequest.BrowserContextId = _contextId;
            }

            string targetId = (await _client.SendAsync(createTargetRequest)
                               .ConfigureAwait(false)).TargetId;
            var target = _browser.TargetsMap[targetId];
            await target.InitializedTask.ConfigureAwait(false);

            return(await target.GetPageAsync().ConfigureAwait(false));
        }
コード例 #13
0
        /// <inheritdoc cref="IBrowser.StartTracingAsync(IPage, TracingOptions)"/>
        public Task StartTracingAsync(IPage page, TracingOptions options = null)
        {
            if (_tracingRecording)
            {
                throw new InvalidOperationException("Cannot start recording trace while already recording trace.");
            }

            _tracingClient = page != null ? ((ChromiumPage)((Page)page).Delegate).Client : _client;

            var defaultCategories = new List <string>
            {
                "-*",
                "devtools.timeline",
                "v8.execute",
                "disabled-by-default-devtools.timeline",
                "disabled-by-default-devtools.timeline.frame",
                "toplevel",
                "blink.console",
                "blink.user_timing",
                "latencyInfo",
                "disabled-by-default-devtools.timeline.stack",
                "disabled-by-default-v8.cpu_profiler",
            };

            var categories = options?.Categories ?? defaultCategories;

            if (options?.Screenshots == true)
            {
                categories.Add("disabled-by-default-devtools.screenshot");
            }

            _tracingPath      = options?.Path;
            _tracingRecording = true;

            return(_tracingClient.SendAsync(new TracingStartRequest
            {
                TransferMode = "ReturnAsStream",
                Categories = string.Join(", ", categories),
            }));
        }
コード例 #14
0
 internal Task InitializeAsync() => _client.SendAsync(new NetworkEnableRequest());