You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VB.net中通过WebView2获取Edge控制台的SM.Player.token值

问题描述

在Edge浏览器按F12打开控制台,输入SM.Player.token可获取目标值,现在需要用VB.NET结合WebView2自动化获取该值,替代手动输入。当前尝试的代码如下:

Dim token As String = ""
Dim script As String = "document.getElementById('SM.Player.token')"
token = "" & WebView2.ExecuteScriptAsync(script).ToString

执行后返回结果为:"System.Threading.Tasks.Task1[System.String]"`,无法拿到实际的token值。

解决方向

1. 修正JavaScript脚本

SM.Player.token是全局变量/对象属性,不是DOM元素,不需要用document.getElementById获取。正确的脚本应该直接返回这个值:

SM.Player.token

如果它是函数的话,需要加括号调用:

SM.Player.token()

2. 正确处理异步方法

WebView2.ExecuteScriptAsync是异步方法,返回的是Task(Of String)类型,直接调用ToString()只会得到任务对象的字符串表示,而不是执行结果。需要等待任务完成:

方法一:在异步方法中使用Await(推荐)

将代码放在标记为Async的方法里:

Async Sub GetToken()
    Dim token As String = ""
    Dim script As String = "SM.Player.token"
    ' 等待异步任务完成,获取实际结果
    Dim result As String = Await WebView2.ExecuteScriptAsync(script)
    ' ExecuteScriptAsync返回的结果是JSON格式字符串,需要解析
    token = Newtonsoft.Json.JsonConvert.DeserializeObject(Of String)(result)
End Sub

方法二:同步环境下使用.Result(不推荐,可能导致死锁)

如果无法使用异步方法,可以用.Result强制等待任务完成,但要注意UI线程阻塞风险:

Dim token As String = ""
Dim script As String = "SM.Player.token"
Dim task As Task(Of String) = WebView2.ExecuteScriptAsync(script)
' 等待任务完成并获取结果
Dim result As String = task.Result
' 解析JSON格式的结果
token = Newtonsoft.Json.JsonConvert.DeserializeObject(Of String)(result)

3. 注意结果解析

ExecuteScriptAsync返回的结果是JSON格式的字符串,比如如果实际token是"abc123",返回的会是"""abc123""",需要用JSON库(比如Newtonsoft.Json)解析成实际的字符串值。

内容的提问来源于stack exchange,提问作者Scott

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:40:22