如何用PowerShell/Bat脚本在Edge设备模拟模式打开网页及实现相关操作?
在Microsoft Edge中实现设备模拟的脚本方案
一、直接启动Edge并进入设备模拟模式的脚本
可以利用Edge的命令行参数直接实现,Bat和PowerShell脚本都支持:
1. Bat脚本示例
@echo off :: 替换为目标网页URL和要模拟的设备名称(如"Nexus 5"、"iPhone 14") set "URL=https://example.com" set "DEVICE_NAME=iPhone 14" :: 启动Edge,自动打开开发者工具并进入指定设备模拟模式 start msedge.exe "%URL%" --auto-open-devtools-for-tabs --device-emulation="deviceName:%DEVICE_NAME%"
参数说明:
--auto-open-devtools-for-tabs:自动为新标签页打开开发者工具--device-emulation="deviceName:XXX":指定模拟设备,设备名称可在Edge开发者工具的设备列表中查看
2. PowerShell脚本示例
$url = "https://example.com" $deviceName = "iPhone 14" # 启动Edge并启用设备模拟 Start-Process "msedge.exe" -ArgumentList "$url --auto-open-devtools-for-tabs --device-emulation=`"deviceName:$deviceName`""
二、对已打开的Edge标签页实现自动化操作(F12+切换设备模拟)
这个需求完全可行,核心是激活Edge窗口后模拟键盘快捷键:
PowerShell脚本示例
# 加载Windows Forms程序集用于发送键盘事件 Add-Type -AssemblyName System.Windows.Forms # 获取运行中的Edge窗口(取第一个非空标题的窗口) $edgeWindow = Get-Process msedge | Where-Object { $_.MainWindowTitle -ne "" } | Select-Object -First 1 if ($edgeWindow) { # 激活Edge窗口 $hwnd = $edgeWindow.MainWindowHandle [void][System.Windows.Forms.User32]::SetForegroundWindow($hwnd) Start-Sleep -Milliseconds 500 # 等待窗口激活 # 发送F12打开开发者工具 [System.Windows.Forms.SendKeys]::SendWait("{F12}") Start-Sleep -Milliseconds 1000 # 等待开发者工具加载完成 # 发送Ctrl+Shift+M切换到设备模拟模式(Edge默认快捷键) [System.Windows.Forms.SendKeys]::SendWait("^+M") } else { Write-Host "未找到运行中的Edge窗口" } # 导入User32.dll的窗口激活方法 Add-Type @" using System; using System.Runtime.InteropServices; public class User32 { [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); } "@
注意事项:
- 若修改过Edge快捷键,需将
Ctrl+Shift+M替换为你设置的设备模拟切换快捷键 - 脚本中的等待时间需根据电脑性能调整,确保操作有足够执行时间
- 运行脚本时Edge窗口不能最小化到托盘,需处于可交互状态
内容的提问来源于stack exchange,提问作者Dood
相关产品推荐
相关产品推荐

