Tuesday, May 7, 2013

Set user-agent string of WebView

To set user-agent string of WebView, call its getSettings().setUserAgentString(ua); where ua is is your user-agent string.

package com.example.androidwebview;

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {
 
 WebView myWebView;
 //final static String myAddr = "http://android-er.blogspot.com";
 //final static String myAddr = "http://developer.android.com/";
 final static String myAddr = "http://whatsmyuseragent.com/";
 
 //Chrome run on Linux Desktop
 //String ua = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31";
 //Chrome run on Android 4.1.1 HTC One X
 //String ua = "Mozilla/5.0 (Linux; Android 4.1.1; HTC One X Build/JRO03C) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.58 Mobile Safari/537.31";
 //Firefox run on Android 3.2.1 HTC Flyer 7" Tablet
 String ua = "Mozilla/5.0 (Android; Tablet; rv:20.0) Gecko/20.0 Firefox/20.0";
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  //setContentView(R.layout.activity_main);
  myWebView = new WebView(this);
  
  myWebView.getSettings().setUserAgentString(ua);
  myWebView.getSettings().setUseWideViewPort(true);
  myWebView.getSettings().setLoadWithOverviewMode(true);
  
  myWebView.getSettings().setJavaScriptEnabled(true);                
  myWebView.setWebViewClient(new MyWebViewClient());
  myWebView.loadUrl(myAddr);
  setContentView(myWebView);
  
 }
 
 private class MyWebViewClient extends WebViewClient {

  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
   view.loadUrl(url);
   return true;
  }
  
 }

}

Set user-agent string of WebView


remark: to check what user-agent your browser set, browse to http://whatsmyuseragent.com/, allows you to view details about your user agent.

download filesDownload the files.


Updated@2019-10-24:

WhatsMyUserAgent.com have made two changes that are important for users:-

#1. now part of WhoIsHostingThis.com
#2. have moved to HTTPS to keep your users safe!

Updated link to 'https://www.whoishostingthis.com/tools/user-agent/'



4 comments:

  1. Great code. Thanks a lot

    ReplyDelete
  2. Very nice code and article, thx very much

    ReplyDelete
  3. how will i use custom name of user agent string..(i want to see my apps name)

    ReplyDelete
  4. hello km muzahid,

    may be here: http://developer.android.com/reference/android/webkit/WebSettings.html#setUserAgentString(java.lang.String)

    ReplyDelete