Search code examples
c#google-chrome-devtoolspuppeteerpuppeteer-sharp

How to use PuppeteerSharp to get the value of performance.timeOrigin?


Using PuppeteerSharp, I am attempting to get the performance.timeOrigin value using the C# code below:

JToken performanceTimeOriginString = await _page.EvaluateFunctionAsync("JSON.stringify(performance.timeOrigin);").ConfigureAwait(false);

I have verified that this works in a JavaScript console: enter image description here

However, when I run the above PuppeteerSharp code, I get the following exception:

System.AggregateException: One or more errors occurred. (Evaluation failed: SyntaxError: Unexpected token ';') ---> PuppeteerSharp.EvaluationFailedException: Evaluation failed: SyntaxError: Unexpected token ';'
at PuppeteerSharp.ExecutionContext.ExecuteEvaluationAsync(String method, Object args)
at PuppeteerSharp.ExecutionContext.RemoteObjectTaskToObject[T](Task`1 remote)
at PuppeteerSharp.DOMWorld.EvaluateFunctionAsync[T](String script, Object[] args)
--- End of inner exception stack trace ---

It was telling me to remove the semicolon (very odd), so I tried that but then got the below exception.

System.AggregateException: One or more errors occurred. (Protocol error (Runtime.callFunctionOn): Given expression does not evaluate to a function) ---> PuppeteerSharp.EvaluationFailedException: Protocol error (Runtime.callFunctionOn): Given expression does not evaluate to a function ---> PuppeteerSharp.MessageException: Protocol error (Runtime.callFunctionOn): Given expression does not evaluate to a function
at PuppeteerSharp.CDPSession.SendAsync(String method, Object args, Boolean waitForCallback)
at PuppeteerSharp.CDPSession.SendAsync[T](String method, Object args)
at PuppeteerSharp.ExecutionContext.ExecuteEvaluationAsync(String method, Object args)
--- End of inner exception stack trace ---

How can I use PuppeteerSharp to get the value of performance.timeOrigin?


Solution

  • You should use EvaluateExpressionAsync.

    _page.EvaluateExpressionAsync("JSON.stringify(performance.timeOrigin)").ConfigureAwait(false);