mercredi 10 janvier 2018

[Return of experience] UWP WebView and playing with it http headers to change the user-agent [C#,WebView,HTTP]

Over the years I have had the opportunity to work a lot with the UWP Webview on Windows Mobile (sic), Desktop, Xbox and HoloLens.

This has given me the opportunity to really see what happens when you play with the user-agent of the WebView.  One would imagine that even if the WebView was used on Desktop / Mobile and Xbox that even if you had used the same user agent for all three platform that everything would work.  This will probably be the case for 90% of your HTTP calls but every now and then this will not be the case.

First a little bit of back story about why did I override the WebViews user-agent, by default it works great, however I encountered a case that when the WebView calls other urls (redirections mainly) on Desktop and Xbox the HTTP headers are lost/ not passed along. Which is why I had to set the user-agent in the first place.

The next issue that I encounter was that I was using the same user-agent on all 3 platforms Desktop/Mobile/Xbox which meant that the url that I was calling thought that for all 3 platforms I was a desktop.  The url that I calling was serving a video media element and depending on which platforms it was being called it would either be using the media stack from the device or the media stack for the webview.

Here are 2 user agents for Xbox One and Windows 10 Desktop devices:
Xbox One
Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/13.10586
The issue that I was having with this user-agent is that on our servers the app was serving the video on the wrong  media stack again. This was because on the Xbox the application would think that it was being run on a Windows Mobile wish is not great. In the end i ended up edit the string as follows "(Windows NT 10.0; Win64; x64; Xbox; Xbox One)" instead of "(Windows Phone 10.0; Android 4.2.1; Xbox; Xbox One)".

Windows 10-based PC using Edge browser
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246

In the end everything ended up working as expected and the Media stack of the device was used and not the WebViewmedia stack.  This however was only achieved by being able to send the correct user-agent to the WebView so that the url called would then give back the correct information.

Happy coding,

Website with all lots of user agents: https://deviceatlas.com/blog/list-of-user-agent-strings