简体   繁体   中英

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

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.

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.

You can try await Task.Delay(-1)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM