Example usage for android.webkit WebSettings setUserAgentString

List of usage examples for android.webkit WebSettings setUserAgentString

Introduction

In this page you can find the example usage for android.webkit WebSettings setUserAgentString.

Prototype

public abstract void setUserAgentString(@Nullable String ua);

Source Link

Document

Sets the WebView's user-agent string.

Usage

From source file:org.microg.gms.auth.login.LoginActivity.java

@SuppressLint("SetJavaScriptEnabled")
private static void prepareWebViewSettings(WebSettings settings) {
    settings.setUserAgentString(settings.getUserAgentString() + MAGIC_USER_AGENT);
    settings.setJavaScriptEnabled(true);
    settings.setSupportMultipleWindows(false);
    settings.setSaveFormData(false);//from w w  w  .  ja  v a2 s.c om
    settings.setAllowFileAccess(false);
    settings.setDatabaseEnabled(false);
    settings.setNeedInitialFocus(false);
    settings.setUseWideViewPort(false);
    settings.setSupportZoom(false);
    settings.setJavaScriptCanOpenWindowsAutomatically(false);
}

From source file:de.trier.infsec.koch.droidsheep.activities.HijackActivity.java

private void setupWebView() {
    webview = (WebView) findViewById(R.id.webviewhijack);
    webview.setWebViewClient(new MyWebViewClient());
    WebSettings webSettings = webview.getSettings();
    webSettings.setUserAgentString("foo");
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAppCacheEnabled(false);
    webSettings.setBuiltInZoomControls(true);
    webview.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            HijackActivity.this.setProgress(progress * 100);
        }// ww  w  .  j ava  2s  .c  o m
    });
}

From source file:com.zbrown.droidsteal.activities.HijackActivity.java

private void setupWebView() {
    webview = (WebView) findViewById(R.id.webviewhijack);
    webview.setWebViewClient(new MyWebViewClient());
    WebSettings webSettings = webview.getSettings();
    webSettings.setUserAgentString(
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36");
    webSettings.setJavaScriptEnabled(true); //Blah blah JavaScript is scary blah blah
    webSettings.setAppCacheEnabled(false);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setDisplayZoomControls(false);
    webview.setWebChromeClient(new WebChromeClient() {
        @Override/*from   w w  w .  j a  va2  s .  c  om*/
        public void onProgressChanged(WebView view, int progress) {
            HijackActivity.this.setProgress(progress * 100);
            int fprogress = (Window.PROGRESS_END) / 100 * progress;
            setProgress(fprogress);

            if (progress == 100) {
                setProgressBarIndeterminateVisibility(false);
            }
        }
    });
}

From source file:at.alladin.rmbt.android.help.RMBTHelpFragment.java

/**
* 
*//* w w w .j  a  va2  s .c  o m*/
@SuppressLint("SetJavaScriptEnabled")
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    super.onCreateView(inflater, container, savedInstanceState);

    final Bundle args = getArguments();

    String url = args.getString(ARG_URL);

    if (url == null || url.length() == 0)
        url = this.getString(R.string.url_help);

    final Activity activity = getActivity();

    final WebView webview = new WebView(activity) {
        @Override
        public boolean onKeyDown(final int keyCode, final KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && canGoBack()) {
                goBack();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
    };

    final WebSettings webSettings = webview.getSettings();
    final String userAgent = AppConstants.getUserAgentString(getActivity());
    if (userAgent != null) {
        webSettings.setUserAgentString(userAgent);
    }
    webSettings.setJavaScriptEnabled(true);

    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(final WebView view, final int errorCode, final String description,
                final String failingUrl) {
            Log.w(getTag(), "error code:" + errorCode);
            Log.d(getTag(), "error desc:" + description);
            Log.d(getTag(), "error url:" + failingUrl);
            webview.loadUrl("file:///android_res/raw/error.html");
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    });

    if (!url.matches("^https?://.*")) {
        final String protocol = ConfigHelper.isControlSeverSSL(activity) ? "https" : "http";
        url = protocol + "://" + url;
    }

    webview.loadUrl(url);

    return webview;
}

From source file:com.owncloud.android.ui.dialog.LoginWebViewDialog.java

@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled")
@Override/*from  www.  j ava 2  s .c o m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log_OC.v(TAG, "onCreateView, savedInsanceState is " + savedInstanceState);

    // Inflate layout of the dialog  
    RelativeLayout ssoRootView = (RelativeLayout) inflater.inflate(R.layout.webview_dialog, container, false); // null parent view because it will go in the dialog layout

    if (mWebView == null) {
        // initialize the WebView
        mWebView = new SsoWebView(getActivity().getApplicationContext());
        mWebView.setFocusable(true);
        mWebView.setFocusableInTouchMode(true);
        mWebView.setClickable(true);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setUserAgentString(MainApp.getUserAgent());
        webSettings.setSaveFormData(false);
        // next two settings grant that non-responsive webs are zoomed out when loaded
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        // next three settings allow the user use pinch gesture to zoom in / out
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setAllowFileAccess(false);

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();

        mWebView.loadUrl(mInitialUrl);
    }

    mWebViewClient.addTargetUrls(mTargetUrls);
    mWebView.setWebViewClient(mWebViewClient);

    // add the webview into the layout
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    ssoRootView.addView(mWebView, layoutParams);
    ssoRootView.requestLayout();

    return ssoRootView;
}

From source file:com.analysedesgeeks.android.WebFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    final View v = inflater.inflate(R.layout.fragment_webview, container, false);

    webview = (WebView) v.findViewById(R.id.webview);

    final WebSettings settings = webview.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);
    settings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
    settings.setSupportZoom(true);//from   w w w . ja  v  a  2 s  . co  m
    settings.setBuiltInZoomControls(true);

    //load a custom user agent 
    //see http://stackoverflow.com/questions/6856814/problems-loading-mobile-twitter-in-webview
    settings.setUserAgentString(
            "Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");

    final View loading = v.findViewById(R.id.loading);

    webview.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(final WebView view, final String url) {
            loading.setVisibility(View.GONE);
        }
    });

    webview.loadUrl(url);

    return v;
}

From source file:com.cerema.cloud2.ui.dialog.SamlWebViewDialog.java

@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled")
@Override//from  w w  w .j  a va2 s .  c o  m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log_OC.v(TAG, "onCreateView, savedInsanceState is " + savedInstanceState);

    // Inflate layout of the dialog  
    RelativeLayout ssoRootView = (RelativeLayout) inflater.inflate(R.layout.sso_dialog, container, false); // null parent view because it will go in the dialog layout

    if (mSsoWebView == null) {
        // initialize the WebView
        mSsoWebView = new SsoWebView(getActivity().getApplicationContext());
        mSsoWebView.setFocusable(true);
        mSsoWebView.setFocusableInTouchMode(true);
        mSsoWebView.setClickable(true);

        WebSettings webSettings = mSsoWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setLoadWithOverviewMode(false);
        webSettings.setSavePassword(false);
        webSettings.setUserAgentString(MainApp.getUserAgent());
        webSettings.setSaveFormData(false);

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();

        mSsoWebView.loadUrl(mInitialUrl);
    }

    mWebViewClient.setTargetUrl(mTargetUrl);
    mSsoWebView.setWebViewClient(mWebViewClient);

    // add the webview into the layout
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    ssoRootView.addView(mSsoWebView, layoutParams);
    ssoRootView.requestLayout();

    return ssoRootView;
}

From source file:com.digitalarx.android.ui.dialog.SamlWebViewDialog.java

@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled")
@Override//  w ww  . j  a  v  a 2s. c o  m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log_OC.d(TAG, "onCreateView, savedInsanceState is " + savedInstanceState);

    // Inflate layout of the dialog  
    RelativeLayout ssoRootView = (RelativeLayout) inflater.inflate(R.layout.sso_dialog, container, false); // null parent view because it will go in the dialog layout

    if (mSsoWebView == null) {
        // initialize the WebView
        mSsoWebView = new SsoWebView(getSherlockActivity().getApplicationContext());
        mSsoWebView.setFocusable(true);
        mSsoWebView.setFocusableInTouchMode(true);
        mSsoWebView.setClickable(true);

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();
        mSsoWebView.loadUrl(mInitialUrl);

        WebSettings webSettings = mSsoWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setLoadWithOverviewMode(false);
        webSettings.setSavePassword(false);
        webSettings.setUserAgentString(OwnCloudClient.USER_AGENT);
        webSettings.setSaveFormData(false);
    }

    mWebViewClient.setTargetUrl(mTargetUrl);
    mSsoWebView.setWebViewClient(mWebViewClient);

    // add the webview into the layout
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    ssoRootView.addView(mSsoWebView, layoutParams);
    ssoRootView.requestLayout();

    return ssoRootView;
}

From source file:system.info.reader.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    resolutions = Properties.resolution(dm);
    Properties.resolution = resolutions[0] + "*" + resolutions[1];
    int tabHeight = 30, tabWidth = 80;
    if (dm.widthPixels >= 480) {
        tabHeight = 40;/*from ww  w . ja v  a2 s .  c  o  m*/
        tabWidth = 120;
    }

    tabHost = getTabHost();
    LayoutInflater.from(this).inflate(R.layout.main, tabHost.getTabContentView(), true);
    tabHost.addTab(
            tabHost.newTabSpec("tab1").setIndicator(getString(R.string.brief)).setContent(R.id.PropertyList));
    tabHost.addTab(
            tabHost.newTabSpec("tab2").setIndicator(getString(R.string.online)).setContent(R.id.ViewServer));
    tabHost.addTab(
            tabHost.newTabSpec("tab3").setIndicator(getString(R.string.apps)).setContent(R.id.sViewApps));
    tabHost.addTab(
            tabHost.newTabSpec("tab4").setIndicator(getString(R.string.process)).setContent(R.id.sViewProcess));
    tabHost.addTab(tabHost.newTabSpec("tab5").setIndicator("Services").setContent(R.id.sViewCpu));
    tabHost.addTab(tabHost.newTabSpec("tab6").setIndicator("Tasks").setContent(R.id.sViewMem));
    //tabHost.addTab(tabHost.newTabSpec("tab7")
    //        .setIndicator("Vending")
    //        .setContent(R.id.sViewDisk));
    AppsText = (TextView) findViewById(R.id.TextViewApps);
    ProcessText = (TextView) findViewById(R.id.TextViewProcess);
    ServiceText = (TextView) findViewById(R.id.TextViewCpu);
    TaskText = (TextView) findViewById(R.id.TextViewMem);

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(tabWidth, tabHeight);
    for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++)
        tabHost.getTabWidget().getChildAt(i).setLayoutParams(lp);

    properList = (ListView) findViewById(R.id.PropertyList);
    Properties.properListItem = new ArrayList<HashMap<String, Object>>();
    properListItemAdapter = new SimpleAdapter(this, Properties.properListItem, R.layout.property_list,
            new String[] { "ItemTitle", "ItemText" }, new int[] { R.id.ItemTitle, R.id.ItemText });
    properList.setAdapter(properListItemAdapter);
    properList.setOnItemClickListener(mpropertyCL);

    //will support app list later
    //appList = (ListView)findViewById(R.id.AppList);
    //Properties.appListItem = new ArrayList<HashMap<String, Object>>();  
    //SimpleAdapter appListItemAdapter = new SimpleAdapter(this, Properties.appListItem,   
    //             R.layout.app_list,  
    //             new String[] {"ItemTitle", "ItemText"},   
    //             new int[] {R.id.ItemTitle, R.id.ItemText}  
    //         );  
    //appList.setAdapter(appListItemAdapter);

    serverWeb = (WebView) findViewById(R.id.ViewServer);
    WebSettings webSettings = serverWeb.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUserAgentString("sys.info.trial" + versionCode);
    webSettings.setTextSize(WebSettings.TextSize.SMALLER);
    serverWeb.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;//this will not launch browser when redirect.
        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    });

    PackageManager pm = getPackageManager();
    try {
        PackageInfo pi = pm.getPackageInfo("sys.info.trial", 0);
        version = "v" + pi.versionName;
        versionCode = pi.versionCode;

        List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);
        nApk = Integer.toString(apps.size());
        apklist = "";
        for (PackageInfo app : apps) {
            apklist += app.packageName + "\t(" + app.versionName + ")\n";
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    showDialog(0);
    initPropList();
    //refresh();
    PageTask task = new PageTask();
    task.execute("");
}

From source file:net.wequick.small.webkit.WebView.java

private void initSettings() {
    WebSettings webSettings = this.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUserAgentString(webSettings.getUserAgentString() + " Native");
    this.addJavascriptInterface(new SmallJsBridge(), "_Small");

    this.setWebChromeClient(new WebChromeClient() {
        @Override//www. j a va 2  s  . c o  m
        public void onReceivedTitle(android.webkit.WebView view, String title) {
            // Call if html title is set
            super.onReceivedTitle(view, title);
            mTitle = title;
            WebActivity activity = (WebActivity) WebViewPool.getContext(view);
            if (activity != null) {
                activity.setTitle(title);
            }
            // May receive head meta at the same time
            initMetas();
        }

        @Override
        public boolean onJsAlert(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            if (context == null)
                return false;

            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onJsConfirm(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.cancel();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = consoleMessage.message();
            if (msg == null)
                return false;
            Uri uri = Uri.parse(msg);
            if (uri != null && null != uri.getScheme() && uri.getScheme().equals(SMALL_SCHEME)) {
                String host = uri.getHost();
                String ret = uri.getQueryParameter(SMALL_QUERY_KEY_RET);
                if (host.equals(SMALL_HOST_POP)) {
                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                } else if (host.equals(SMALL_HOST_EXEC)) {
                    if (mOnResultListener != null) {
                        mOnResultListener.onResult(ret);
                    }
                }
                return true;
            }
            Log.d(consoleMessage.sourceId(),
                    "line" + consoleMessage.lineNumber() + ": " + consoleMessage.message());
            return true;
        }

        @Override
        public void onCloseWindow(android.webkit.WebView window) {
            super.onCloseWindow(window);
            close(new OnResultListener() {
                @Override
                public void onResult(String ret) {
                    if (ret.equals("false"))
                        return;

                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                }
            });
        }
    });

    this.setWebViewClient(new android.webkit.WebViewClient() {

        private final String ANCHOR_SCHEME = "anchor";

        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                return super.shouldOverrideUrlLoading(view, url);
            }

            Boolean hasStarted = mHasStartedUrl.get(url);
            if (hasStarted != null && hasStarted) {
                // location redirected before page finished
                return super.shouldOverrideUrlLoading(view, url);
            }

            HitTestResult hit = view.getHitTestResult();
            if (hit != null) {
                Uri uri = Uri.parse(url);
                if (uri.getScheme().equals(ANCHOR_SCHEME)) {
                    // Scroll to anchor
                    int anchorY = Integer.parseInt(uri.getHost());
                    view.scrollTo(0, anchorY);
                } else {
                    Small.openUri(uri, WebViewPool.getContext(view));
                }
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mHasStartedUrl.put(url, true);

            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                mInjected = false;
            }
            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageStarted(WebViewPool.getContext(view), (WebView) view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(android.webkit.WebView view, String url) {
            super.onPageFinished(view, url);
            mHasStartedUrl.remove(url);

            HitTestResult hit = view.getHitTestResult();
            if (hit != null && hit.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
                // Triggered by user clicked
                Uri uri = Uri.parse(url);
                String anchor = uri.getFragment();
                if (anchor != null) {
                    // If is an anchor, calculate the content offset by DOM
                    // and call native to adjust WebView's offset
                    view.loadUrl(JS_PREFIX + "var y=document.body.scrollTop;"
                            + "var e=document.getElementsByName('" + anchor + "')[0];" + "while(e){"
                            + "y+=e.offsetTop-e.scrollTop+e.clientTop;e=e.offsetParent;}" + "location='"
                            + ANCHOR_SCHEME + "://'+y;");
                }
            }

            if (!mInjected) {
                // Re-inject Small Js
                loadJs(SMALL_INJECT_JS);
                initMetas();
                mInjected = true;
            }

            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageFinished(WebViewPool.getContext(view), (WebView) view, url);
            }
        }

        @Override
        public void onReceivedError(android.webkit.WebView view, int errorCode, String description,
                String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.e("Web", "error: " + description);
            if (sWebViewClient != null && failingUrl.equals(mLoadingUrl)) {
                sWebViewClient.onReceivedError(WebViewPool.getContext(view), (WebView) view, errorCode,
                        description, failingUrl);
            }
        }
    });
}