Functions/New-PWSession.ps1


function New-PWSession
{
    <#
    .SYNOPSIS
    Creates a new Playwright session.
 
    .DESCRIPTION
    The `New-PWSession` function creates a new Playwright session. It launches a new Chromium browser, creates a new
    context, and returns a `pscustomobject` containing the browser, context, and page.
 
    .EXAMPLE
    $session = New-PWSession
 
    Demonstrates launching a new Playwright session.
 
    .EXAMPLE
    $session = New-PWSession -Headless
 
    Demonstrates launching a new Playwright session in headless mode.
    #>

    [CmdletBinding()]
    [OutputType([Microsoft.Playwright.IPage])]
    param(
        [switch] $Headless
    )

    $pw = [Microsoft.Playwright.Playwright]::CreateAsync().GetAwaiter().GetResult()
    $browser = $pw.Chromium.LaunchAsync([Microsoft.Playwright.BrowserTypeLaunchOptions]@{
        Headless = $Headless
    }).GetAwaiter().GetResult()
    $context = $browser.NewContextAsync().GetAwaiter().GetResult()
    $page = $context.NewPageAsync().GetAwaiter().GetResult()

    return [PSCustomObject]@{
        Browser = $browser
        Context = $context
        Page = $page
    }
}