一、介绍

该脚本经过测试可运行在Windows10,Chrome浏览器版本为128的环境下

作用为实时检测Chrome浏览器是否打开了指定的网页,如没有打开或者浏览器被关闭,将重新打开浏览器并打开网页,或直接在当前浏览器打开指定的网页

脚本有两个版本:浏览器网址必须要完全匹配(完全匹配);浏览器网址后缀可变更,但网址需一致(模糊匹配)

二、脚本代码

新建一个*.ps1文件,将如下代码复制进去保存即可

1、模糊匹配版本

# Chrome 浏览器监控脚本(前缀匹配版)
# 参数设置
$targetUrl = "https://www.example.com"  # 替换为您要监控的网址
$checkInterval = 30  # 检查间隔(秒)

# 检查 Chrome 是否已安装
$chromePath = ""
if (Test-Path "C:\Program Files\Google\Chrome\Application\chrome.exe") {
    $chromePath = "C:\Program Files\Google\Chrome\Application\chrome.exe"
} elseif (Test-Path "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe") {
    $chromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
} else {
    Write-Host "未找到 Chrome 浏览器,请确保已安装 Chrome。"
    exit
}

# 监控功能
Write-Host "开始监控是否打开了指定网页: $targetUrl"
Write-Host "检查间隔: $checkInterval 秒"
Write-Host "按 Ctrl+C 停止监控"

# 远程调试端口
$debugPort = 9222
$debugUrl = "http://localhost:$debugPort/json"

# 记录状态
$lastOpenAttempt = $null
$debugModeConfirmed = $false

# 函数:检查远程调试是否可用
function Test-ChromeDebugMode {
    try {
        $response = Invoke-RestMethod -Uri $debugUrl -TimeoutSec 8
        return $true
    } catch {
        return $false
    }
}

# 函数:关闭所有 Chrome 进程
function Stop-AllChrome {
    $chromeProcesses = Get-Process -Name "chrome" -ErrorAction SilentlyContinue
    if ($chromeProcesses) {
        Write-Host "正在关闭所有 Chrome 进程..."
        $chromeProcesses | Stop-Process -Force
        Start-Sleep -Seconds 2
        # 确认所有 Chrome 进程已关闭
        $remainingProcesses = Get-Process -Name "chrome" -ErrorAction SilentlyContinue
        if ($remainingProcesses) {
            Write-Host "仍有 Chrome 进程在运行,强制关闭..."
            $remainingProcesses | Stop-Process -Force
            Start-Sleep -Seconds 1
        }
        Write-Host "所有 Chrome 进程已关闭"
    }
}

# 函数:以调试模式启动 Chrome
function Start-ChromeWithDebug {
    try {
        Write-Host "正在以调试模式启动 Chrome..."
        $process = Start-Process -FilePath $chromePath -ArgumentList "--remote-debugging-port=$debugPort", $targetUrl -PassThru
        Start-Sleep -Seconds 3
        # 确认调试模式已启动
        if (Test-ChromeDebugMode) {
            Write-Host "Chrome 已以调试模式启动 (PID: $($process.Id))"
            $script:debugModeConfirmed = $true
            return $true
        } else {
            Write-Host "警告: Chrome 已启动但调试模式未确认"
            return $false
        }
    } catch {
        Write-Host "以调试模式启动 Chrome 失败: $($_.Exception.Message)"
        return $false
    }
}

# 函数:使用远程调试 API 打开新标签页
function Open-NewTabWithDebugAPI {
    try {
        # 获取所有标签页信息
        $tabs = Invoke-RestMethod -Uri $debugUrl -TimeoutSec 3
        
        # 查找浏览器目标(Chrome 128 可能需要使用正确的目标)
        $browserTarget = $tabs | Where-Object { $_.type -eq "browser" -or $_.url -eq "" }
        
        if ($browserTarget) {
            # 使用正确的调试 URL
            $debuggerUrl = $browserTarget.webSocketDebuggerUrl
            if (-not $debuggerUrl) {
                # 如果没有 WebSocket URL,尝试使用常规的调试 URL
                $debuggerUrl = $browserTarget.devtoolsFrontendUrl
            }
            
            # 如果找到了调试 URL,使用它来打开新标签页
            if ($debuggerUrl) {
                # 提取目标 ID
                if ($debuggerUrl -match "ws://") {
                    # 这是 WebSocket URL,我们需要使用不同的方法
                    # 对于 Chrome 128,我们可以直接导航到调试器并创建新标签页
                    Write-Host "找到 WebSocket 调试 URL,但需要更复杂的实现"
                    return $false
                } else {
                    # 尝试使用 /json/new 端点(如果可用)
                    try {
                        $newTabUrl = "http://localhost:$debugPort/json/new?$targetUrl"
                        $newTab = Invoke-RestMethod -Uri $newTabUrl -Method Get -TimeoutSec 3
                        Write-Host "通过远程调试 API 打开了新标签页"
                        return $true
                    } catch {
                        Write-Host "使用 /json/new 端点失败: $($_.Exception.Message)"
                    }
                }
            }
        }
        
        # 如果上述方法失败,尝试使用更直接的方法
        # 对于 Chrome 128,我们可以直接创建一个新的标签页
        try {
            # 使用更简单的方法 - 直接启动新标签页
            Start-Process -FilePath $chromePath -ArgumentList $targetUrl
            Write-Host "已通过直接启动方式打开新标签页"
            return $true
        } catch {
            Write-Host "直接启动方式也失败: $($_.Exception.Message)"
            return $false
        }
    } catch {
        Write-Host "使用远程调试 API 打开新标签页失败: $($_.Exception.Message)"
        return $false
    }
}

try {
    # 初始启动 - 确保以调试模式运行
    if (-not (Test-ChromeDebugMode)) {
        Stop-AllChrome
        Start-ChromeWithDebug
    } else {
        Write-Host "检测到 Chrome 已在调试模式下运行"
        $debugModeConfirmed = $true
    }
    
    while ($true) {
        $isOpened = $false
        
        # 检查远程调试模式是否仍然可用
        if (-not (Test-ChromeDebugMode)) {
            Write-Host "$(Get-Date -Format 'HH:mm:ss') - Chrome 调试模式不可用"
            $debugModeConfirmed = $false
            
            # 关闭所有 Chrome 并重新以调试模式启动
            Stop-AllChrome
            if (Start-ChromeWithDebug) {
                # 成功重启,继续检查
                Start-Sleep -Seconds 3
            } else {
                # 重启失败,等待下次循环再试
                Start-Sleep -Seconds $checkInterval
                continue
            }
        }
        
        # 使用 Chrome 远程调试功能获取标签页信息
        try {
            $response = Invoke-RestMethod -Uri $debugUrl -TimeoutSec 3
            foreach ($page in $response) {
                # 修改:使用前缀匹配而不是完全匹配
                # 检查页面URL是否以目标URL开头
                if ($page.url.StartsWith($targetUrl)) {
                    $isOpened = $true
                    Write-Host "$(Get-Date -Format 'HH:mm:ss') - 检测到目标网页已打开 (URL: $($page.url))"
                    $lastOpenAttempt = $null  # 重置尝试记录
                    break
                }
            }
        } catch {
            Write-Host "$(Get-Date -Format 'HH:mm:ss') - 远程调试连接失败"
            $debugModeConfirmed = $false
        }
        
        # 如果未检测到目标网页,则打开它
        if (-not $isOpened) {
            $currentTime = Get-Date
            # 避免频繁尝试打开,至少间隔10秒
            if (-not $lastOpenAttempt -or (($currentTime - $lastOpenAttempt).TotalSeconds -gt 10)) {
                Write-Host "$(Get-Date -Format 'HH:mm:ss') - 未检测到目标网页,正在打开..."
                $lastOpenAttempt = $currentTime
                
                # 优先使用远程调试 API 打开新标签页
                if ($debugModeConfirmed) {
                    if (Open-NewTabWithDebugAPI) {
                        Write-Host "成功通过远程调试 API 打开新标签页"
                    } else {
                        Write-Host "远程调试 API 打开新标签页失败,尝试直接启动新 Chrome 实例"
                        try {
                            Start-Process -FilePath $chromePath -ArgumentList $targetUrl
                            Write-Host "已启动新 Chrome 实例"
                        } catch {
                            Write-Host "启动新 Chrome 实例失败: $($_.Exception.Message)"
                        }
                    }
                } else {
                    Write-Host "调试模式未确认,尝试直接启动新 Chrome 实例"
                    try {
                        Start-Process -FilePath $chromePath -ArgumentList $targetUrl
                        Write-Host "已启动新 Chrome 实例"
                    } catch {
                        Write-Host "启动新 Chrome 实例失败: $($_.Exception.Message)"
                    }
                }
                
                # 等待页面加载
                Start-Sleep -Seconds 3
            } else {
                Write-Host "$(Get-Date -Format 'HH:mm:ss') - 等待重试打开网页..."
            }
        }
        
        # 等待下一次检查
        Start-Sleep -Seconds $checkInterval
    }
}
catch {
    Write-Host "监控已停止: $($_.Exception.Message)"
}
finally {
    Write-Host "脚本结束"
}

2、完全匹配版本

# Chrome 浏览器监控脚本(远程调试优先版)
# 参数设置
$targetUrl = "https://www.example.com"  # 替换为您要监控的网址
$checkInterval = 30  # 检查间隔(秒)

# 检查 Chrome 是否已安装
$chromePath = ""
if (Test-Path "C:\Program Files\Google\Chrome\Application\chrome.exe") {
    $chromePath = "C:\Program Files\Google\Chrome\Application\chrome.exe"
} elseif (Test-Path "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe") {
    $chromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
} else {
    Write-Host "未找到 Chrome 浏览器,请确保已安装 Chrome。"
    exit
}

# 监控功能
Write-Host "开始监控是否打开了指定网页: $targetUrl"
Write-Host "检查间隔: $checkInterval 秒"
Write-Host "按 Ctrl+C 停止监控"

# 远程调试端口
$debugPort = 9222
$debugUrl = "http://localhost:$debugPort/json"

# 记录状态
$lastOpenAttempt = $null
$debugModeConfirmed = $false

# 函数:检查远程调试是否可用
function Test-ChromeDebugMode {
    try {
        $response = Invoke-RestMethod -Uri $debugUrl -TimeoutSec 8
        return $true
    } catch {
        return $false
    }
}

# 函数:关闭所有 Chrome 进程
function Stop-AllChrome {
    $chromeProcesses = Get-Process -Name "chrome" -ErrorAction SilentlyContinue
    if ($chromeProcesses) {
        Write-Host "正在关闭所有 Chrome 进程..."
        $chromeProcesses | Stop-Process -Force
        Start-Sleep -Seconds 2
        # 确认所有 Chrome 进程已关闭
        $remainingProcesses = Get-Process -Name "chrome" -ErrorAction SilentlyContinue
        if ($remainingProcesses) {
            Write-Host "仍有 Chrome 进程在运行,强制关闭..."
            $remainingProcesses | Stop-Process -Force
            Start-Sleep -Seconds 1
        }
        Write-Host "所有 Chrome 进程已关闭"
    }
}

# 函数:以调试模式启动 Chrome
function Start-ChromeWithDebug {
    try {
        Write-Host "正在以调试模式启动 Chrome..."
        $process = Start-Process -FilePath $chromePath -ArgumentList "--remote-debugging-port=$debugPort", $targetUrl -PassThru
        Start-Sleep -Seconds 3
        # 确认调试模式已启动
        if (Test-ChromeDebugMode) {
            Write-Host "Chrome 已以调试模式启动 (PID: $($process.Id))"
            $script:debugModeConfirmed = $true
            return $true
        } else {
            Write-Host "警告: Chrome 已启动但调试模式未确认"
            return $false
        }
    } catch {
        Write-Host "以调试模式启动 Chrome 失败: $($_.Exception.Message)"
        return $false
    }
}

# 函数:使用远程调试 API 打开新标签页
function Open-NewTabWithDebugAPI {
    try {
        # 获取所有标签页信息
        $tabs = Invoke-RestMethod -Uri $debugUrl -TimeoutSec 3
        
        # 查找浏览器目标(Chrome 128 可能需要使用正确的目标)
        $browserTarget = $tabs | Where-Object { $_.type -eq "browser" -or $_.url -eq "" }
        
        if ($browserTarget) {
            # 使用正确的调试 URL
            $debuggerUrl = $browserTarget.webSocketDebuggerUrl
            if (-not $debuggerUrl) {
                # 如果没有 WebSocket URL,尝试使用常规的调试 URL
                $debuggerUrl = $browserTarget.devtoolsFrontendUrl
            }
            
            # 如果找到了调试 URL,使用它来打开新标签页
            if ($debuggerUrl) {
                # 提取目标 ID
                if ($debuggerUrl -match "ws://") {
                    # 这是 WebSocket URL,我们需要使用不同的方法
                    # 对于 Chrome 128,我们可以直接导航到调试器并创建新标签页
                    Write-Host "找到 WebSocket 调试 URL,但需要更复杂的实现"
                    return $false
                } else {
                    # 尝试使用 /json/new 端点(如果可用)
                    try {
                        $newTabUrl = "http://localhost:$debugPort/json/new?$targetUrl"
                        $newTab = Invoke-RestMethod -Uri $newTabUrl -Method Get -TimeoutSec 3
                        Write-Host "通过远程调试 API 打开了新标签页"
                        return $true
                    } catch {
                        Write-Host "使用 /json/new 端点失败: $($_.Exception.Message)"
                    }
                }
            }
        }
        
        # 如果上述方法失败,尝试使用更直接的方法
        # 对于 Chrome 128,我们可以直接创建一个新的标签页
        try {
            # 使用更简单的方法 - 直接启动新标签页
            Start-Process -FilePath $chromePath -ArgumentList $targetUrl
            Write-Host "已通过直接启动方式打开新标签页"
            return $true
        } catch {
            Write-Host "直接启动方式也失败: $($_.Exception.Message)"
            return $false
        }
    } catch {
        Write-Host "使用远程调试 API 打开新标签页失败: $($_.Exception.Message)"
        return $false
    }
}

try {
    # 初始启动 - 确保以调试模式运行
    if (-not (Test-ChromeDebugMode)) {
        Stop-AllChrome
        Start-ChromeWithDebug
    } else {
        Write-Host "检测到 Chrome 已在调试模式下运行"
        $debugModeConfirmed = $true
    }
    
    while ($true) {
        $isOpened = $false
        
        # 检查远程调试模式是否仍然可用
        if (-not (Test-ChromeDebugMode)) {
            Write-Host "$(Get-Date -Format 'HH:mm:ss') - Chrome 调试模式不可用"
            $debugModeConfirmed = $false
            
            # 关闭所有 Chrome 并重新以调试模式启动
            Stop-AllChrome
            if (Start-ChromeWithDebug) {
                # 成功重启,继续检查
                Start-Sleep -Seconds 3
            } else {
                # 重启失败,等待下次循环再试
                Start-Sleep -Seconds $checkInterval
                continue
            }
        }
        
        # 使用 Chrome 远程调试功能获取标签页信息
        try {
            $response = Invoke-RestMethod -Uri $debugUrl -TimeoutSec 3
            foreach ($page in $response) {
                # 比较 URL,忽略可能的尾部斜杠差异
                $pageUrl = $page.url.TrimEnd('/')
                $compareUrl = $targetUrl.TrimEnd('/')
                
                if ($pageUrl -eq $compareUrl) {
                    $isOpened = $true
                    Write-Host "$(Get-Date -Format 'HH:mm:ss') - 检测到目标网页已打开"
                    $lastOpenAttempt = $null  # 重置尝试记录
                    break
                }
            }
        } catch {
            Write-Host "$(Get-Date -Format 'HH:mm:ss') - 远程调试连接失败"
            $debugModeConfirmed = $false
        }
        
        # 如果未检测到目标网页,则打开它
        if (-not $isOpened) {
            $currentTime = Get-Date
            # 避免频繁尝试打开,至少间隔10秒
            if (-not $lastOpenAttempt -or (($currentTime - $lastOpenAttempt).TotalSeconds -gt 10)) {
                Write-Host "$(Get-Date -Format 'HH:mm:ss') - 未检测到目标网页,正在打开..."
                $lastOpenAttempt = $currentTime
                
                # 优先使用远程调试 API 打开新标签页
                if ($debugModeConfirmed) {
                    if (Open-NewTabWithDebugAPI) {
                        Write-Host "成功通过远程调试 API 打开新标签页"
                    } else {
                        Write-Host "远程调试 API 打开新标签页失败,尝试直接启动新 Chrome 实例"
                        try {
                            Start-Process -FilePath $chromePath -ArgumentList $targetUrl
                            Write-Host "已启动新 Chrome 实例"
                        } catch {
                            Write-Host "启动新 Chrome 实例失败: $($_.Exception.Message)"
                        }
                    }
                } else {
                    Write-Host "调试模式未确认,尝试直接启动新 Chrome 实例"
                    try {
                        Start-Process -FilePath $chromePath -ArgumentList $targetUrl
                        Write-Host "已启动新 Chrome 实例"
                    } catch {
                        Write-Host "启动新 Chrome 实例失败: $($_.Exception.Message)"
                    }
                }
                
                # 等待页面加载
                Start-Sleep -Seconds 3
            } else {
                Write-Host "$(Get-Date -Format 'HH:mm:ss') - 等待重试打开网页..."
            }
        }
        
        # 等待下一次检查
        Start-Sleep -Seconds $checkInterval
    }
}
catch {
    Write-Host "监控已停止: $($_.Exception.Message)"
}
finally {
    Write-Host "脚本结束"
}

三、一点小改进

正常情况下,我们运行这个脚本就是为了防止指定的网页被人关闭,但该脚本运行时会被显示在前台,我们可以新建一个bat文件,输入以下代码,,将"C:\path\to\script.ps1"改为你的脚本目录即可,

PowerShell.exe -WindowStyle Hidden -File "C:\path\to\script.ps1"

或可以将该bat文件直接和脚本文件放在同一个目录下,那么代码就为(注意改脚本文件名)

PowerShell.exe -WindowStyle Hidden -File ".\script.ps1"