iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🗂

How to Automate Browser Operations Using PowerShell and CDP in a Restricted Environment

に公開

Introduction

There are cases where browser automation is necessary when performing a restricted play that prohibits downloading libraries or applications.
In the past, it was possible to automate browsers using Internet Explorer's COM.
Today, however, it is generally no longer possible to automate Internet Explorer.

This article introduces a method for browser automation using Edge's Chrome DevTools Protocol (CDP).

This article is intended for those who can write PowerShell in an organization where downloading libraries or applications is prohibited.
Also, in environments without such restrictions, choosing a different method is more appropriate.

The environment is as follows:
OS: Windows 11
PSVersion: 5.1.26100.6584

Automating Edge with PowerShell + CDP

Automation Contents

  • Open Zenn's top page
  • Enter "test" in the search box and press Enter
  • Output the list of articles to the standard output

Sample Code

Sample Code
# powershell -File cdp.ps1

# Get the path to Edge
function Get-EdgePath {
    $paths = @()

    $pf = [Environment]::GetEnvironmentVariable('ProgramFiles')
    if ($pf) {
        $paths += (Join-Path $pf 'Microsoft\Edge\Application\msedge.exe')
    }

    $pf86 = [Environment]::GetEnvironmentVariable('ProgramFiles(x86)')
    if ($pf86) {
        $paths += (Join-Path $pf86 'Microsoft\Edge\Application\msedge.exe')
    }

    foreach ($p in $paths) {
        if (Test-Path $p) {
            return $p
        }
    }

    $cmd = Get-Command 'msedge.exe' -ErrorAction SilentlyContinue
    if ($cmd -and $cmd.Path) {
        return $cmd.Source
    }

    throw "Microsoft Edge (msedge.exe) could not be found."
}

Add-Type -AssemblyName System.Net.Http
# Not needed in PowerShell 5.1
# Add-Type -AssemblyName System.Net.WebSockets

$global:cdpSocket = [System.Net.WebSockets.ClientWebSocket]::new()
$global:cdpCts    = New-Object System.Threading.CancellationTokenSource
$global:cdpId     = 0

# Send a CDP command
function Send-CdpCommand {
    param(
        [int]$Id,
        [string]$Method,
        [hashtable]$Params
    )

    if (-not $Params) { $Params = @{} }

    $payload = @{
        id     = $Id
        method = $Method
        params = $Params
    } | ConvertTo-Json -Depth 5

    $bytes = [System.Text.Encoding]::UTF8.GetBytes($payload)
    $seg   = New-Object System.ArraySegment[byte] (, $bytes)

    $global:cdpSocket.SendAsync(
        $seg,
        [System.Net.WebSockets.WebSocketMessageType]::Text,
        $true,
        $global:cdpCts.Token
    ).Wait()
}

# Receive a message from CDP
function Receive-CdpMessageForId {
    param([int]$ExpectedId)

    # Buffer for receiving a single message
    $buffer = New-Object byte[] 8192

    while ($true) {
        # ← Key point: how to create ArraySegment[byte]
        $segment = New-Object "System.ArraySegment[byte]" -ArgumentList (, $buffer)

        $result = $global:cdpSocket.ReceiveAsync(
            $segment,
            $global:cdpCts.Token
        ).Result

        $json = [System.Text.Encoding]::UTF8.GetString($buffer, 0, $result.Count)

        # Occasional corrupt/unexpected JSON from notifications, so use try-catch
        try {
            $msg = $json | ConvertFrom-Json
        } catch {
            continue
        }

        if ($msg.id -eq $ExpectedId) {
            return $msg
        }

        # Ignore notifications with a different id (e.g., Page.loadEventFired) and loop again
    }
}


# Send a command to CDP and wait for the response
function Invoke-Cdp {
    param(
        [string]$Method,
        [hashtable]$Params
    )

    $global:cdpId++
    $id = $global:cdpId
    Send-CdpCommand -Id $id -Method $Method -Params $Params
    return (Receive-CdpMessageForId -ExpectedId $id)
}

# Connect to CDP
function Connect-Cdp {
    $targets = Invoke-RestMethod http://localhost:9222/json/list
    $target  = $targets[0]
    $wsUrl   = $target.webSocketDebuggerUrl

    $uri = [Uri]$wsUrl
    $global:cdpSocket.ConnectAsync($uri, $global:cdpCts.Token).Wait()

    $global:cdpId = 0
    Invoke-Cdp -Method "Page.enable" -Params @{}
    Invoke-Cdp -Method "DOM.enable"  -Params @{}
}

# Get the center coordinates of an element
function Get-ElementCenter {
    param($model)

    $xs = @()
    $ys = @()

    for ($i = 0; $i -lt $model.content.Count; $i += 2) {
        $xs += [double]$model.content[$i]
        $ys += [double]$model.content[$i + 1]
    }

    $cx = ($xs | Measure-Object -Average).Average
    $cy = ($ys | Measure-Object -Average).Average

    return @{ X = $cx; Y = $cy }
}

# Click the specified element
function Invoke-CdpClickBySelector {
    param(
        [string]$Selector
    )
    # For click events, refer to pyppeteer below
    # https://github.com/pyppeteer/pyppeteer/blob/7dc91ee5173d3836f77800a3774beeaf2b448c0e/pyppeteer/input.py#L285
    $doc    = Invoke-Cdp -Method "DOM.getDocument" -Params @{}
    $rootId = $doc.result.root.nodeId

    $q = Invoke-Cdp -Method "DOM.querySelector" -Params @{
        nodeId  = $rootId
        selector = $Selector
    }

    $nodeId = $q.result.nodeId
    if (-not $nodeId) {
        throw "No element matching selector '$Selector'."
    }

    $box    = Invoke-Cdp -Method "DOM.getBoxModel" -Params @{ nodeId = $nodeId }
    $center = Get-ElementCenter -model $box.result.model

    Invoke-Cdp -Method "Input.dispatchMouseEvent" -Params @{
        type       = "mousePressed"
        x          = $center.X
        y          = $center.Y
        button     = "left"
        clickCount = 1
    }

    Invoke-Cdp -Method "Input.dispatchMouseEvent" -Params @{
        type       = "mouseReleased"
        x          = $center.X
        y          = $center.Y
        button     = "left"
        clickCount = 1
    }
}

# Wait until the specified element is visible
function Wait-CdpElementBySelector {
    param(
        [string]$Selector,
        [int]$TimeoutMs  = 10000,
        [int]$IntervalMs = 250
    )

    $elapsed = 0
    while ($elapsed -lt $TimeoutMs) {
        $doc    = Invoke-Cdp -Method "DOM.getDocument" -Params @{}
        $rootId = $doc.result.root.nodeId

        $q = Invoke-Cdp -Method "DOM.querySelector" -Params @{
            nodeId  = $rootId
            selector = $Selector
        }

        if ($q.result.nodeId) {
            return $true
        }

        Start-Sleep -Milliseconds $IntervalMs
        $elapsed += $IntervalMs
    }

    throw "Timeout: Selector '$Selector' could not be found."
}

# Insert text into the specified element
function Send-CdpText {
    param(
        [string]$Text
    )

    # Insert text into the focused element
    Invoke-Cdp -Method "Input.insertText" -Params @{ text = $Text }
}

# Press Enter
function Send-CdpEnter {
    # keyDown
    Invoke-Cdp -Method "Input.dispatchKeyEvent" -Params @{
        type                  = "keyDown"
        key                   = "Enter"
        code                  = "Enter"
        windowsVirtualKeyCode = 13
        nativeVirtualKeyCode  = 13
        text = "`r"
    }

    # keyUp
    Invoke-Cdp -Method "Input.dispatchKeyEvent" -Params @{
        type                  = "keyUp"
        key                   = "Enter"
        code                  = "Enter"
        windowsVirtualKeyCode = 13
        nativeVirtualKeyCode  = 13
        text = "`r"
    }
}

# Wait until specific text appears
function Wait-CdpText {
    param(
        [string]$Text,
        [int]$TimeoutMs = 10000,
        [int]$IntervalMs = 300
    )

    $elapsed = 0

    while ($elapsed -lt $TimeoutMs) {

        # Search for the string in JS and return... escape if input is untrusted
        $js = @"
document.body.innerText.includes("$Text")
"@

        $r = Invoke-Cdp -Method "Runtime.evaluate" -Params @{
            expression    = $js
            returnByValue = $true
        }

        if ($r.result.result.value -eq $true) {
            Write-Host "Text '$Text' detected."
            return $true
        }

        Start-Sleep -Milliseconds $IntervalMs
        $elapsed += $IntervalMs
    }

    throw "Timeout waiting for text '$Text'"
}


# Launch Edge for automation
$edgePath = Get-EdgePath
$userDataDir = Join-Path $env:TEMP "edge-devtools-profile"
if (-not (Test-Path $userDataDir)) {
    New-Item -ItemType Directory -Path $userDataDir | Out-Null
}

$edge = Start-Process -FilePath $edgePath -ArgumentList @(
    "--remote-debugging-port=9222",
    "--user-data-dir=$userDataDir",
    "--no-first-run",
    "--new-window"
) -PassThru

Start-Sleep -Seconds 2

# Connect to CDP
Connect-Cdp


# STEP 1: navigate https://zenn.dev/
Invoke-Cdp -Method "Page.navigate" -Params @{ url = "https://zenn.dev/" }

# Wait for display
Wait-CdpElementBySelector -Selector "#header-search path"

# STEP 2: click search icon (#header-search)
Invoke-CdpClickBySelector -Selector "#header-search"

# STEP 3: waitForElement strong (popular topics)
Wait-CdpText "人気のトピック"

# STEP 4: click input form (#input-search-form)
Invoke-CdpClickBySelector -Selector "#input-search-form"
#Start-Sleep -Milliseconds 500

# STEP 5: change value -> "test"
Send-CdpText -Text "test"
Send-CdpEnter

# STEP 6: waitForElement wait for article tag in search results
Wait-CdpElementBySelector -Selector "article"


# Get the list of articles using JavaScript
$js = @'
Array.from(document.querySelectorAll("[class*='ArticleListItem_title']"))
    .map(x => x.innerText)
'@
$r = Invoke-Cdp -Method "Runtime.evaluate" -Params @{
    expression    = $js
    returnByValue = $true
}
$r.result.result.value | ForEach-Object {
    Write-Host $_
}

# Close the CDP WebSocket
$global:cdpSocket.CloseAsync(
    [System.Net.WebSockets.WebSocketCloseStatus]::NormalClosure,
    "done",
    $global:cdpCts.Token
).Wait()

$global:cdpSocket.Dispose()
$global:cdpCts.Dispose()

if ($edge -and !$edge.HasExited) {
    $edge.Kill()
}

Code Explanation

Launching Edge and Connecting to CDP

# Connect to CDP
function Connect-Cdp {
    $targets = Invoke-RestMethod http://localhost:9222/json/list
    $target  = $targets[0]
    $wsUrl   = $target.webSocketDebuggerUrl

    $uri = [Uri]$wsUrl
    $global:cdpSocket.ConnectAsync($uri, $global:cdpCts.Token).Wait()

    $global:cdpId = 0
    Invoke-Cdp -Method "Page.enable" -Params @{}
    Invoke-Cdp -Method "DOM.enable"  -Params @{}
}

# Launch Edge for automation
$edgePath = Get-EdgePath
$userDataDir = Join-Path $env:TEMP "edge-devtools-profile"
if (-not (Test-Path $userDataDir)) {
    New-Item -ItemType Directory -Path $userDataDir | Out-Null
}

$edge = Start-Process -FilePath $edgePath -ArgumentList @(
    "--remote-debugging-port=9222",
    "--user-data-dir=$userDataDir",
    "--no-first-run",
    "--new-window"
) -PassThru

Start-Sleep -Seconds 2

# Connect to CDP
Connect-Cdp

This code launches the browser with the remote-debugging-port option.
It uses Invoke-RestMethod to retrieve data from json/list.
The response contains the webSocketDebuggerUrl, so we connect using System.Net.WebSockets.ClientWebSocket.
If too many tabs are open, this may not work.

Sending and Receiving CDP Messages

# Send a CDP command
function Send-CdpCommand {
    param(
        [int]$Id,
        [string]$Method,
        [hashtable]$Params
    )

    if (-not $Params) { $Params = @{} }

    $payload = @{
        id     = $Id
        method = $Method
        params = $Params
    } | ConvertTo-Json -Depth 5

    $bytes = [System.Text.Encoding]::UTF8.GetBytes($payload)
    $seg   = New-Object System.ArraySegment[byte] (, $bytes)

    $global:cdpSocket.SendAsync(
        $seg,
        [System.Net.WebSockets.WebSocketMessageType]::Text,
        $true,
        $global:cdpCts.Token
    ).Wait()
}

# Receive a message from CDP
function Receive-CdpMessageForId {
    param([int]$ExpectedId)

    # Buffer for receiving a single message
    $buffer = New-Object byte[] 8192

    while ($true) {
        # ← Key point: how to create ArraySegment[byte]
        $segment = New-Object "System.ArraySegment[byte]" -ArgumentList (, $buffer)

        $result = $global:cdpSocket.ReceiveAsync(
            $segment,
            $global:cdpCts.Token
        ).Result

        $json = [System.Text.Encoding]::UTF8.GetString($buffer, 0, $result.Count)

        # Occasional corrupt/unexpected JSON from notifications, so use try-catch
        try {
            $msg = $json | ConvertFrom-Json
        } catch {
            continue
        }

        if ($msg.id -eq $ExpectedId) {
            return $msg
        }

        # Ignore notifications with a different id (e.g., Page.loadEventFired) and loop again
    }
}


# Send a command to CDP and wait for the response
function Invoke-Cdp {
    param(
        [string]$Method,
        [hashtable]$Params
    )

    $global:cdpId++
    $id = $global:cdpId
    Send-CdpCommand -Id $id -Method $Method -Params $Params
    return (Receive-CdpMessageForId -ExpectedId $id)
}

Using Invoke-Cdp, we send a message to CDP and wait for its response.
Receive-CdpMessageForId is a simple implementation, so it may not work with long messages or messages split across multiple frames.

Mouse Click

# Get the center coordinates of an element
function Get-ElementCenter {
    param($model)

    $xs = @()
    $ys = @()

    for ($i = 0; $i -lt $model.content.Count; $i += 2) {
        $xs += [double]$model.content[$i]
        $ys += [double]$model.content[$i + 1]
    }

    $cx = ($xs | Measure-Object -Average).Average
    $cy = ($ys | Measure-Object -Average).Average

    return @{ X = $cx; Y = $cy }
}

# Click the specified element
function Invoke-CdpClickBySelector {
    param(
        [string]$Selector
    )
    # For click events, refer to pyppeteer below
    # https://github.com/pyppeteer/pyppeteer/blob/7dc91ee5173d3836f77800a3774beeaf2b448c0e/pyppeteer/input.py#L285
    $doc    = Invoke-Cdp -Method "DOM.getDocument" -Params @{}
    $rootId = $doc.result.root.nodeId

    $q = Invoke-Cdp -Method "DOM.querySelector" -Params @{
        nodeId  = $rootId
        selector = $Selector
    }

    $nodeId = $q.result.nodeId
    if (-not $nodeId) {
        throw "No element matching selector '$Selector'."
    }

    $box    = Invoke-Cdp -Method "DOM.getBoxModel" -Params @{ nodeId = $nodeId }
    $center = Get-ElementCenter -model $box.result.model

    Invoke-Cdp -Method "Input.dispatchMouseEvent" -Params @{
        type       = "mousePressed"
        x          = $center.X
        y          = $center.Y
        button     = "left"
        clickCount = 1
    }

    Invoke-Cdp -Method "Input.dispatchMouseEvent" -Params @{
        type       = "mouseReleased"
        x          = $center.X
        y          = $center.Y
        button     = "left"
        clickCount = 1
    }
}

Invoke-CdpClickBySelector clicks the center of the specified element.

For click events, code from pyppeteer and similar libraries is helpful.
https://github.com/pyppeteer/pyppeteer/blob/7dc91ee5173d3836f77800a3774beeaf2b448c0e/pyppeteer/input.py#L285

Text Input


# Insert text into the specified element
function Send-CdpText {
    param(
        [string]$Text
    )

    # Insert text into the focused element
    Invoke-Cdp -Method "Input.insertText" -Params @{ text = $Text }
}

# Press Enter
function Send-CdpEnter {
    # keyDown
    Invoke-Cdp -Method "Input.dispatchKeyEvent" -Params @{
        type                  = "keyDown"
        key                   = "Enter"
        code                  = "Enter"
        windowsVirtualKeyCode = 13
        nativeVirtualKeyCode  = 13
        text = "`r"
    }

    # keyUp
    Invoke-Cdp -Method "Input.dispatchKeyEvent" -Params @{
        type                  = "keyUp"
        key                   = "Enter"
        code                  = "Enter"
        windowsVirtualKeyCode = 13
        nativeVirtualKeyCode  = 13
        text = "`r"
    }
}

To insert text into the specified element, use Input.insertText. This also works with full-width characters.

To press the Enter key, use Input.dispatchKeyEvent.

Enumerating Content with JavaScript

# Get the list of articles using JavaScript
$js = @'
Array.from(document.querySelectorAll("[class*='ArticleListItem_title']"))
    .map(x => x.innerText)
'@
$r = Invoke-Cdp -Method "Runtime.evaluate" -Params @{
    expression    = $js
    returnByValue = $true
}
$r.result.result.value | ForEach-Object {
    Write-Host $_
}

Use Runtime.evaluate to embed JavaScript and retrieve the result for display.

Summary

In this article, we confirmed a method for browser automation on Windows 11 without installing anything, using Edge's Chrome DevTools Protocol (CDP).
Since this is a simple implementation, there are some issues regarding exception handling and termination, but it confirms that browser automation is possible without installing anything.
We used Edge this time, but if Chrome is installed, it should work by simply changing the path.

Discussion