Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
ui.WebView User Agent?
-
Looking through the documentation I can see that there's no standard way to set the user agent of the webview client. My question: is it possible to use some Objective C functions to set the user agent of the webview? I would like to set a custom user agent in an effort to get desktop versions of websites vs the default mobile site.
If anyone else has this same goal, the only workaround I can imagine working (but haven't tried) is setting the WebView width to be wider than the actual screen. This would only work if the website displays desktop version of sites based on the screen size rather than the user agent.
-
On a bit of a tangent, I was looking at the ui.py and webbrowser.py files. One thing I saw in webbrowser.py was the OperaCoast, Mercury, etc classes. @omz could you tell us what these do or how to use them?
-
Apparantly you can set useragent, app-wide. The following sets the app default, initializes a webview, then sets the default back, so the rest of the app is unaffected.
from objc_util import * import ui import time def webview_with_useragent(agentstring=None, *args, **kwargs): d=ObjCClass('NSUserDefaults').standardUserDefaults() old=d.volatileDomainForName_('NSRegistrationDomain') if agentstring: d.registerDefaults_({'UserAgent':agentstring}) w= ui.WebView(*args,**kwargs) w.load_url('http://') # webview needs to be initialized time.sleep(1) # there maybe a more robust way... wait before setting old default d.setVolatileDomain_forName_(old,'NSRegistrationDomain') return w if __name__=='__main__': w=webview_with_useragent('hello') w.load_url('http://www.whatsmyua.info/') w.present('panel') time.sleep(2) #verify it persists... w.load_url('https://www.whatismybrowser.com/detect/what-is-my-user-agent') #verify standard webview not affected w2=ui.WebView() w2.load_url('http://www.whatsmyua.info/') w2.present('panel')
-
btw, those Chrome, etc let you launch other browser apps, externally. i.e open Chrome app.
-
Some additional info ...
- Don't try to do it via
NSMutableURLRequest
&setValue:forHTTPHeaderField:
, doesn't work,UIWebView
overwrites it. - When
UIWebView
will be replaced withWKWebView
(in Pythonista), it will be much easier because of customUserAgent property.
- Don't try to do it via