# Close Webview2 app if running

# Direct Microsoft download link

$url = "https://msedge.sf.dl.delivery.mp.microsoft.com/filestreamingservice/files/a8f877a9-3070-4fbd-a1e1-735444bf6f79/Microsoft.WebView2.FixedVersionRuntime.138.0.3351.121.x64.cab"

$temp = Join-Path $env:TEMP "Microsoft.WebView2.FixedVersionRuntime.138.0.3351.121.x64.cab"

$dest = "C:\Program Files (x86)\Microsoft\EdgeWebView\Application\138.0.3351.121"

# Download CAB to temp folder

Write-Host "Downloading WebView2 runtime... please wait, this can take a while depending on your connection." -ForegroundColor Yellow

Invoke-WebRequest -Uri $url -OutFile $temp

# Create destination folder

Write-Host "Creating destination folder..." -ForegroundColor Yellow

New-Item -ItemType Directory -Path $dest -Force | Out-Null

# Extraction notice

Write-Host "Extracting files... please wait, this step may take some time." -ForegroundColor Yellow

expand $temp -F:* $dest

# Flatten folder if nested

$subdirs = Get-ChildItem $dest -Directory

$filesAtRoot = Get-ChildItem $dest -File

if ($subdirs.Count -eq 1 -and $filesAtRoot.Count -eq 0) {

$nested = $subdirs[0].FullName

Move-Item -Path (Join-Path $nested '*') -Destination $dest -Force

Remove-Item $nested -Recurse -Force

# Set machine-wide environment variable

Write-Host "Setting WebView2 environment variable..." -ForegroundColor Yellow

setx /M WEBVIEW2_BROWSER_EXECUTABLE_FOLDER $dest

# Final message

Write-Host ""

Write-Host "WebView2 fix installed successfully." -ForegroundColor Green

Write-Host "Please restart the app that failed with webview2 and test the connection." -ForegroundColor Yellow