grafana / xk6-browser

k6 extension that adds support for browser automation and end-to-end web testing via the Chrome Devtools Protocol
https://grafana.com/docs/k6/latest/javascript-api/k6-experimental/browser/
GNU Affero General Public License v3.0
337 stars 42 forks source link

Implement `BrowserContext.addInitScript(script[, arg])` #8

Open robingustafsson opened 2 years ago

robingustafsson commented 2 years ago

Add support for BrowserContext.addInitScript(script[, arg]), to set script to run on every new page creation or navigation nd every new frame attachment in browser context.

Relevant links:

ka3de commented 1 year ago

As an update to this issue, I have PR #719 as work in progress to implement this, but there are some decisions that I took that I believe should be mentioned here and maybe discussed:

In regards of source maps (ref: 1, 2): For the case on which init script is specified through a path to the actual script file in FS, Playwright includes the sourceURL pragma at the end of the script. By my understanding this will allow users to debug the script from the browser tools if required.

In the case of xk6-browser, I personally don't think this is probably an important feature for our use cases, but could be useful and is worth adding considering the low cost of doing it.

In regards of CDP's experimental fields for worldName and includeCommandLineAPI: These fields are supported as experimental by CDP for the Page.addScriptToEvaluateOnNewDocument spec. As per Playwright's implementation, the worldName parameter is supported somehow in internal methods, but is not exposed to end users for the addInitScript functionality.

In our case my initial approach is to not support this by now, considering that, if we stick to the Playwright's addInitScript spec, this will be defined by us internally, and unless we have distinctions on different world definitions I don't think it makes sense. Do you foresee situations on which we should make distinctions for the world scope of execution, for example between the main and utility worlds, for the case of init scripts @inancgumus, @ankur22 ?

In regards of removing currently defined init scripts: Playwright implements an internal method that allows to remove all previously defined init scripts for the context. From what I could check they use this method internally in order to reset browser contexts. In order to do that, all the identifiers returned for every init script sent to the browser through CDP's addInitScript method must be stored.

In our case, similarly to the previous point argument, I decided to not implement this by now if we don't have a use case or requirement for it. See my TODO comment.

ankur22 commented 1 year ago

We're unblocking and deprioritizing this issue as we've not had any feedback from users as to whether this is actually useful.