Skip to content

Instantly share code, notes, and snippets.

@mattdot
Last active November 17, 2017 03:52
Show Gist options
  • Save mattdot/3b53af7756c061e06f60623c766f657a to your computer and use it in GitHub Desktop.
Save mattdot/3b53af7756c061e06f60623c766f657a to your computer and use it in GitHub Desktop.
Set the UserAgent for a UWP WebView
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace UA
{
public static class UserAgent
{
const int URLMON_OPTION_USERAGENT = 0x10000001;
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkGetSessionOption(int dwOption, StringBuilder pBuffer, int dwBufferLength, ref int pdwBufferLength, int dwReserved);
public static string GetUserAgent()
{
int capacity = 255;
var buf = new StringBuilder(capacity);
int length = 0;
UrlMkGetSessionOption(URLMON_OPTION_USERAGENT, buf, capacity, ref length, 0);
return buf.ToString();
}
public static void SetUserAgent(string agent)
{
var hr = UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, agent, agent.Length, 0);
var ex = Marshal.GetExceptionForHR(hr);
if(null != ex)
{
throw ex;
}
}
public static void AppendUserAgent(string suffix)
{
SetUserAgent(GetUserAgent() + suffix);
}
}
}
@OvestLabs
Copy link

Wow... This works! Is this safe? Will this pass certification?

@jerone
Copy link

jerone commented Nov 5, 2017

@OvestLabs Did you get this passed in the Store?

@mms-
Copy link

mms- commented Nov 14, 2017

Passes certification without any issues, but the app crashes once installed from the store! With Unresolved P/Invoke method 'urlmon.dll!UrlMkGetSessionOption', this is when targeting Fall Creators Update

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment