我目前使用這種方法,改編自最初爲windows phone提供的方法。它給出了正確的結果,並從WebView對象的實例中直接得到它,因此讓我更有信心具有正確的價值。
private static string s_userAgent = null;
// Get the default UserAgent which webviews use on this platform.
public async Task<string> GetUserAgent()
{
if (s_userAgent == null)
{
const string Html = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"">
<html>
<head>
<script language=""javascript"" type=""text/javascript"">
function notifyUA() { window.external.notify(navigator.userAgent); }
</script>
</head>
<body onload=""notifyUA();""></body>
</html>";
SemaphoreSlim signal_done = new SemaphoreSlim(0, 1);
var wv = new WebView();
wv.ScriptNotify += (sender, args) =>
{
s_userAgent = args.Value;
// set signal, to show we've done
signal_done.Release();
};
wv.NavigateToString(Html);
// wait for signal
await signal_done.WaitAsync();
Debug.WriteLine("GetUserAgent() called. User agent from WebView: \n{0}", s_userAgent);
}
return s_userAgent;
}
我的評論變得太大了,所以增加了一個可以擴展你的答案。有一個upvote。 – Stajs