Common methods of WebView in Android application development Note _android

Source: Internet
Author: User
Tags reflection static class blank page

Basic use
using WebView usually requires a network, so you need to add access to the network

<uses-permission android:name= "Android.permission.INTERNET"/>

1. How to load a URL

Webview.loadurl ("http://www.baidu.com");

It should be noted that do not omit the previous http://, omitted, some ROM webview will fail to load
2. Load the HTML in assets

Webview.loadurl ("file:///android_asset/xxx.html")

3. Load a piece of javascript

Webview.loadurl ("javascript:" + ${js_code})

4. Provide local method for JS
as follows, provides a Showtoast method for JavaScript

private static class Javajs {
  private context context;
  Javajs {
    This.context = context;
  }
  @JavascriptInterface public
  void Showtoast (String str) {
    toast.maketext (context, str, toast.length_long). Show ();
  }
Webview.addjavascriptinterface (The new Javajs (this), "Javajs");


<script type= "Text/javascript" >
  javajs.showtoast ("Toast from JS");
</script>

Attention:

    • The method provided to JavaScript must be public, otherwise JS cannot access
    • The method provided to JavaScript will be executed in a webview-managed thread, so that the method's thread safety is guaranteed. (Toast is supported for show () in a non-UI thread, so the Showtoast method above is OK)
    • The method provided to JavaScript must be added @JavascriptInterface
    • Before Android 4.2,api 17, JavaScript could perform some dangerous operations by reflecting Java objects. such as reflection to runtime, then execute shell command
    • Although @javascriptinterface was added in API 17, before API 17, we still recommend adding the annotation to JavaScript. (JSR-175 stipulates that the runtime annotation missing, then directly ignored, and will not throw classnotfoundexception)
    • For devices prior to Android 4.2, we recommend that you do not provide a method via Addjavascriptinterface to JavaScript and pass the Removejavascriptinterface (" Searchboxjavabridge_ ") to remove the Java object that WebView added.

5. Page Jump

Webview.setwebviewclient (New Webviewclient () {

  @Override public
  boolean shouldoverrideurlloading (WebView View, String URL) {
    if (uri.parse (URL). GetHost (). Equals ("www.xxx.com")) {
      //own page, load return directly using WebView
      false;
    }
    Other company pages, using the browser to open
    Intent Intent = new Intent (Intent.action_view, Uri.parse (URL));
    StartActivity (intent);
    return true;
  }
});

6. Visit History fallback

@Override Public
boolean onKeyDown (int keycode, keyevent event) {
  if (keycode = = keyevent.keycode_back) & & Webview.cangoback ()) {
    webview.goback ();
    return true;
  }
  Return Super.onkeydown (KeyCode, event);
}

7. Output JavaScript log information in Logcat
rewriting the Onconsolemessage method in Webchromeclient

@Override Public
Boolean onconsolemessage (Consolemessage consolemessage) {
  log.d ("WebView"), Consolemessage.message () + "JS line:" + consolemessage.linenumber ());
  return true;
}

8. Support for JavaScript alert box alert
rewriting the Onjsalert method in Webchromeclient

@Override Public
Boolean Onjsalert (webview view, string URL, String message, final Jsresult result) {
  new Alertdia Log. Builder (Mainactivity.this)
      . Settitle ("Jsalert"). Setmessage (Message
      ).
      Setpositivebutton ("OK", New Dialoginterface.onclicklistener () {
        @Override public
        void OnClick (dialoginterface dialog, int which) { C15/>result.confirm ();
        }
      })
      . Setcancelable (False)
      . Show ();
  return true;
}

9. Support JavaScript Confirmation box confirm
rewriting the Onjsconfirm method in Webchromeclient

@Override Public
Boolean onjsconfirm (webview view, string URL, String message, final Jsresult result) {
  new ALERTD Ialog. Builder (Mainactivity.this)
      . Settitle ("Jsconfirm"). Setmessage (Message
      )
      . Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {
        @Override public
        void OnClick (dialoginterface dialog, int which) {
          Result.confirm ();
        }
      })
      . Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {
        @Override public
        void OnClick ( Dialoginterface dialog, int which) {
          result.cancel ();
        }
      })
      . Setcancelable (False)
      . Show ();
  return true;
}

10. Support JavaScript Question box prompt
rewriting the Onjsprompt method in Webchromeclient

@Override Public
Boolean onjsprompt (webview view, string URL, String message, String defaultvalue, Final Jspromptresu Lt result) {
  final edittext et = new EditText (mainactivity.this);
  Et.settext (defaultvalue);
  New Alertdialog.builder (Mainactivity.this)
      . Settitle (message).
      Setview (ET)
      . Setpositivebutton ("OK", New Dialoginterface.onclicklistener () {
        @Override public
        void OnClick (dialoginterface dialog, int which) {
          result.confirm (Et.gettext (). toString ());
        }
      )
      . Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {
        @Override public
        void OnClick ( Dialoginterface dialog, int which) {
          result.cancel ();
        }
      })
      . Setcancelable (False)
      . Show ();
  return true;
}

11. Show Blank Page

Webview.loadurl ("About:blank");
This method allows WebView to draw only a white background and release the resources used before the page is loaded and stop the execution of JavaScript before

12. Clear return Stack Webview.clearhistory
13. Get Access History list Webview.copybackforwardlist
14. Download Webview.setdownloadlistener
15.pauseTimers, OnPause, Resumetimers, Onresume

Pausetimers, OnPause Stop parsing, javascript execution, and so on. The difference is that OnPause is only used to invoke its webview, while pausetimers acts on all webview in the current application.
Resumetimers, Onresume Recovery parsing, JavaScript execution, and so on. The difference is that Onresume is only used to invoke its webview, while resumetimers acts on all webview in the current application.

Common settings
1. Security related (remove unnecessary javabridge)

This Java bridge was added by WebView itself
//Before API 17, JavaScript can be reflected through Java objects, performing some unsafe operations
Webview.removejavascriptinterface ("Searchboxjavabridge_");

2.js related

Setting supports JavaScript, default is False
websettings.setjavascriptenabled (true);

3. Scaling related

Enable WebView to scale the page by gesture or zoom controller, the default is True
//This setting does not affect Webview.zoomin () and Webview.zoomout ()
Websettings.setsupportzoom (true);

Setting uses the default zoom controller, the default is False
Websettings.setbuiltinzoomcontrols (true);

Does not display the default//Zoom control view, the default is True
Websettings.setdisplayzoomcontrols (false);
Load picture Policy related

//Set whether the picture is automatically loaded by default ' true ' and if set to ' false ', all pictures will not be loaded, including local pictures.
Websettings.setloadsimagesautomatically (true);

Sets whether the network picture is blocked from loading, the default is ' false ', and if set to ' true ', then the network picture will not load. (Can be set to true first and then set to False to speed the page load)
Websettings.setblocknetworkimage (false);

Sets whether to prevent the load of network resources (not just pictures), default is ' false ', if set to ' true ', js,css on the network, pictures, and so on will not load
websettings.setblocknetworkloads ( FALSE);

4. Rendering related

Set the priority of the render thread
//The method is discarded after Api 18, the priority is managed by WebView
//But it is still recommended that it be set to high to increase page rendering speed
Websettings.setrenderpriority (Renderpriority.high);
Viewport related

//settings using wide viewpoint, default is False
//android browser and chrome for Android setting is ' true '
// The default setting for WebView is ' false '
//If set to ' true ', the available width of the Web page is ' 980px ' and can be set
//If set to ' false ' by meta data. Then the available areas are related to the WebView display area.
Websettings.setusewideviewport (true);

If the WebView content is wider than the width of the display area, the content is narrowed to fit the width of the display area, which defaults to False
Webview.setloadwithoverviewmode (true);
<!--If Websettings.getusewideviewport is true, you can set Viewport--> <!--by using Meta for
example, set the available width to 480px, and the zoom feature is disabled-->
 
 

The effect is similar to the following:

<meta name= "viewport" content= "Width=device-width"/>

Note: The PX here is different from the usual pixel, and he is very similar to the DP concept. See Mozilla

Front-End storage related settings (facilitate front-end engineers to store data on the client)

Support H5 application cache function
websettings.setappcacheenabled (true);
Set Application cache storage path (usually store js,css, pictures, etc.)
websetting.setappcachepath ("xxx");

Support for H5 session storage and local storage
websettings.setdomstorageenabled (true);

Supports JavaScript read, write db
websettings.setdatabaseenabled (true);
Set JS to create the path of the db file, Api 19 after the abandonment, directly have WebView management
websettings.setdatabasepath ("xxx");

5. Cache-Related Settings

When setting load resources, how to use the cache
///default setting is: Websettings.load_default
///When the WebView load a page normally, if the cache hits and does not expire, then use cached data, otherwise load from the network , when Webview.goback (), if a cache hit is used directly, does not verify that
the expiration//available other settings are not verified: Load_cache_else_network, Load_no_cache, load_cache_only
Websettings.setcachemodel (Websettings.load_default);

6.cookie related

public static void Syncookies (context context, String URL) {
  Cookiemanager Cookiemanager = cookiemanager.getinstance ();
  Cookiemanager.setacceptcookie (TRUE);//default is True 
  Cookiemanager.setcookie (url, cookies);
  if (Build.VERSION.SDK_INT <) {
    cookiesyncmanager.createinstance (context). sync ();
  } else {
    Cookiemanager.flush ();
  }



Addjavascriptinterface Security Issues
1. Ways to provide native interface for JavaScript

The Android WebView provides a addjavascriptinterface way to create a javabridge for JavaScript.
For example, provide JS with a Showtoast method:

private static class Javajs {
  private context context;
  Javajs {
    This.context = context;
  }
  @JavascriptInterface public
  void Showtoast (String str) {
    toast.maketext (context, str, toast.length_long). Show ();
  }
Webview.addjavascriptinterface (The new Javajs (this), "Javajs");


<script type= "Text/javascript" >
  javajs.showtoast ("Toast from JS");
</script>

2. Security issues

Before Api 17, after WebView provided Java objects for JavaScript, you could use JavaScript code to invoke the Java Reflection API to perform some hack operations, leading to security issues. (<font color=red> Note: </font> A lower version of WebView will add a Searchboxjavabridge_ object of its own, usually we need to remove it ourselves)
After Api 17, WebView prevents JavaScript calls from adding @javascriptinterface methods to avoid these problems. (<font color=red> Note: </font> recommend that you always add @javascriptinterface instead of being concerned about the API version, Because annotation is missing and does not cause classnotfoundexception, it is simply ignored by the JVM.
Examples of security issues (uninstalling micro-letters via JavaScript)

Through reflection can do a lot of things, such as UserInfo such objects, if he is a single case, then it is easy to access the user's username, mailbox, mobile phone number and other information.
A simple page is shown here, and when the HTML is opened via WebView, the micro-mail on the phone is unloaded (provided that the app has root privileges).

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.