Rayrun
← Back to Discord Forum

Trigger in page JavaScript function?

vortex.penguinposted in #help-playwright
Open in Discord
vortex.penguin
vortex.penguin

In a Playwright test what is the recommended method to execute JavaScript that is already loaded in the page (such as a global library, or page specific function)?

So if my page has JavaScript in it that creates a function named pageFunction on load. How do I then call/trigger that function from a Playwright test?

I tried page.evaluate but that returns an undefined method error. It's unable to find the pageFunction at all.

Thanks for your help.

This thread is trying to answer question "How can I execute JavaScript that is already loaded in a page using Playwright?"

5 replies

Hi, one example:

await page.evaluate(() =>
    ((window as any).__ARGOS__ as ArgosGlobal).prepareForScreenshot(),
  );

It works, so if it does not for you it means the function is not present on window

vortex.penguin
vortex.penguin

@gregberge Without Typescript would that example be:

await page.evaluate(() => window.pageFunction())
vortex.penguin
vortex.penguin

If so that didn't function in previous attempts. The function is a simple function in the global scope. It is defined as:

const pageFunction = (arg) => { ... }
@vortex.penguin: You have to attach it to window to be able to call it in Playwright, the scope you are talking is « lost ». Attach it to window and it should solve your problem.

You have to attach it to window to be able to call it in Playwright, the scope you are talking is « lost ». Attach it to window and it should solve your problem.

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.