Search code examples
puppeteer-sharp

Timeout with EvaluateExpressionAsync<>?


I'm using Puppeteer sharp to render reports and part of that is executing user provided javascript to prepare the data for the report.

I use AddScriptTagAsync to add the scripts to the page then call the user provided script before rendering the report.

If the user provided javascript has an issue that causes an infinite loop (for example) then my call to EvaluateExpressionAsync could await forever:

await page.EvaluateExpressionAsync<dynamic>($"Prepare({DataObject});")

I can't pass a cancellation token to EvaluateExpressionAsync so I can't control it and there appear to be no timeouts available for this method.

I would like to limit it to a controllable number of seconds and then have it timeout.

Any suggestions on how to do this would be very much appreciated.


Solution

  • You would use WaitForExpressionAsync.
    The idea of this method is executing the expression over a period of time until the result is truthy. But if you make sure that your expression will always return a truthy value, WaitForExpressionAsync will timeout using the timeout you pass as an option.