How to prevent the browser from closing while running code in Playwright Tests in Javascript
Asked Answered
I

6

9

I'm trying to log the network calls in the browser. For my use case I require the browser to be in an open state and should be closed only with the scripts. I am currently using the page.pause() function to prevent the browser from automatically closing. Is there any other way to prevent the browser from closing automatically.

test('Verify home page Load event',async({page})=>{
//const browser = await chromium.launchPersistentContext("",{headless:false});
await page.goto("https://samplesite.com")


await page.on('request',req=>{
    const requestUrl = req.url();
    if(requestUrl.indexOf("google-analytics.com/collect")>-1){
        console.log("Intercepted:->"+requestUrl);
        
    }else{            
        req.continue
    }        
}) 

await page.pause();

})

I tried checking out this [link] (How to keep browser opening by the end of the code running with playwright-python?) for python but could not apply it to JS.

Incorrupt answered 1/6, 2022 at 13:9 Comment(0)
C
5

I tried to use await page.pause() and it doesn't work for me, but I found the tricky way, and it works well, just put at the end of your test:

await new Promise(() => {})

Reference on the link.

Cholent answered 15/12, 2022 at 12:55 Comment(0)
A
4

Similar to what was described in the answer to the python question, you need to keep your script alive somehow. This answer describes a couple of ways to do that.

However, page.pause() is definitely the recommended approach- it exists precisely for this kind of situation where you need to inspect the browser while your script is executing. Your script also has some problems- as it stands when you encounter your target request you are logging something but not calling request.continue() (note that this a method, not a property). That will cause all requests to hang indefinitely until it is continued or aborted.

You probably want to do something like this:

await page.route('**/*', (route, request) => {
    const rurl = request.url();
    if (rurl.includes('google-analytics.com/collect')) {
        console.log(`Intercepted request to ${rurl}`);
        // Do other stuff?
    }
    route.continue();
});

It's not clear what you are trying to accomplish from your snippet- if you just need to wait for a particular request to fire, you can use either: page.waitForRequest or page.waitForResponse, and do away with worrying about keeping the browser open.

Antiphlogistic answered 1/6, 2022 at 16:40 Comment(0)
M
2

You can try await Task.Delay(-1)

Myronmyrrh answered 1/6, 2022 at 16:29 Comment(2)
This is a good solution for PlayWright .NETBimah
This sorta works, but Playwright still closes the browser automatically. If you google, you will see tons of people asking how to prevent playwright from closing the browser. So far I've found no reliable solutions.Recreant
G
1

I've had success with the afterEach code below. Basic, but looks to see if the test reported an error and then disables the test timeout and adds @joyful's unresolving promise to simply hold position. Obviously, does not work in parallel or allow the full test suite to run. Note: afterEach appears to run before any of the error conditions output, so we need to manually output those errors to see what went wrong. These only seemed to be useful from their stack.

test.afterEach(async ({ context, extensionId }, testInfo) => {
  const notPassed = testInfo.status !== 'passed';
  const hasError = testInfo.error !== undefined;

  const stayOpen = (notPassed || hasError);

  console.log(...testInfo.errors.map((e) => e.stack));

  if (stayOpen) {
    console.error('\n*** Error detected, holding open browser for debugging. Press CTRL+C to exit. ***');
    testInfo.setTimeout(0); // Disables any test timeout
    await new Promise(() => {}); // Never resolves
  }
});
Gaud answered 10/7, 2023 at 16:0 Comment(0)
E
0

Try setting PW_TEST_REUSE_CONTEXT env var. E.g., in VS Code: enter image description here

Eirena answered 8/8, 2024 at 16:5 Comment(0)
M
0

If you use VSCode with "Playwright Test for VSCode" extension enabled (https://marketplace.visualstudio.com/items?itemName=ms-playwright.playwright)

  • you can tick "Show browser" and it will keep browser open.

enter image description here

Magus answered 20/9, 2024 at 11:58 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.