WebView interaction with JavaScript-Android

Source: Internet
Author: User

WebView interaction with JavaScript-Android

 

In our work, we need to use WebView to interact with javascript. Below we will introduce a simple requirement.

Let's take a look at it first:

 

Requirements:

1. click a button to go to The WebView loading interface. If you want to share this interface with other platforms, the share button will be displayed on the current interface. If you do not need to share the interface, the share button is not displayed.

2. There is a login button on the H5 interface, click Login,

2.1 if you have not logged on to the console, you can call the logon page. After Successful Logon, the login is displayed on the H5 page.

2.2 If you log on, the current login is displayed on the H5 page.

1. Make webview support js calls.

 

webview.addJavascriptInterface(new JsHost(JsActivity.this, mHandler, webview), jsObject);

 

JsHost is a custom class, And jsObject is the object for calling the client js method on the H5 page (the name is also custom, as long as it is the same as the name of the object used by H5javascriprt ).

 

2. Share requirements.

After the H5 page is loaded, the H5 page calls the client's sharing method (this method is used to indicate whether to share and share the content to the client), and then controls whether the sharing button is displayed.

H5 page commit Crip method:

 

Window. onload = function share () {// share var json = {'isshare': 0, 'sharecontent': 'sharing content '}; // do not share var noShare = {'isshare':-1}; window. jsObject. toShare (json );}

 

This is the H5 javascript method used to call the client.

Window: indicates the object of the current page.

Window. onload indicates that the subsequent method is called after the current H5 page is loaded.

Json: The json string to be shared.

Noshare: json string indicating not to share the amount

JsObject: A javascript Object defined by the client.

ToShare (json): the javascript method of the client, so that the client can receive the json string. (here the json string to be shared is transmitted)

 

Define the javascript sharing method in the client's JsHost

 

/*** Sharing method ** @ param json */@ JavascriptInterface public void toShare (String json) {Log. d (TAG, web: + json); try {JSONObject jsonObject = new JSONObject (json); int isShare = jsonObject. optInt (isShare); if (isShare = 0) {// indicates that mHandler needs to be shared. sendEmptyMessage (0);} else if (isShare =-1) {// indicates that mHandler does not need to be shared. sendEmptyMessage (1) ;}} catch (JSONException e) {Log. d (TAG, resolution exception );}}

Add the annotation that identifies javascript, @ JavascriptInerface

 

Parse the passed json string and use the Handler object to send messages to control whether the share button is displayed.

 

MHandler is defined in the JsActivity method and passed to the JsHost class through the addJavascriprtInterface method set in WebView.

JsActivty:

Activity_js.xml

 

 
      
   
 


 

 

Private Handler mHandler = new Handler () {@ Override public void handleMessage (Message msg) {if (msg. what = 0) {// display share btnShare. setVisibility (View. VISIBLE); // display the share button} else if (msg. what = 1) {// hide the share button btnShare. setVisibility (View. GONE); // hide the share button} else if (msg. what = 2) {// call to log on to Intent intent = new Intent (JsActivity. this, LoginActivity. class); startActivityForResult (intent, JsActivity. RESULT_ OK);} super. handleMessage (msg );}};

 

 

3. login requirements

3.1 click Login. If no login is found, the login page pops up.

Log on to the H5 page and call the js method of the client.

 

 

function isLogin() {var name = window.jsObject.requestToken();document.getElementById(loginName).value = name;}


Click log on and call the isLogin () method in javascript. In the isLogin method, call the client's requestToken () method. This requestToken () has a return value, and the return value is the name of the current login.

 

 

Client requestToken Method

 

/*** Request sender ** @ return */@ JavascriptInterface public String requestToken () {if (TextUtils. isEmpty (App. getName () {mHandler. sendEmptyMessage (2);} Log. d (TAG, login name + name = + App. getName (); return TextUtils. isEmpty (App. getName ())? Not logged on: App. getName ();}

 

 

The information of the person who writes the App operation to the login, including the information of the person who writes the login and the information of the person who reads the login.
If App. getName () is used to obtain the name of the login user, if it is null, call the logon interface notification using the mHandelr method. At the same time, the current login user is returned to the H5 page.

 

Intent intent = new Intent(JsActivity.this, LoginActivity.class);                startActivityForResult(intent, JsActivity.RESULT_OK);

Enable the logon page using startActivityForResult

 

For how to use startActivityForResult, see: Click

Take a look at the login page:

Activity_login.xml

 

     
          
           
        
    
   
      
          
           
        
    
   
  
  
 

Click the login button to perform the login operation.

 

 

private void login() {        String name = editName.getText().toString().trim();        String pass = editPass.getText().toString().trim();        if (TextUtils.isEmpty(name)) {            Toast.makeText(getApplicationContext(), name is empty, Toast.LENGTH_SHORT).show();            return;        } else if (TextUtils.isEmpty(pass)) {            Toast.makeText(getApplicationContext(), pass is empty, Toast.LENGTH_SHORT).show();            return;        } else {            App.writeLoginInfo(name, pass);            setResult(JsActivity.RESULT_OK);            finish();        }    }

After successful login, the name and pass are stored in the App.

 

 

public class App extends Application {    private static SharedPreferences sharedPreferences;    @Override    public void onCreate() {        super.onCreate();        sharedPreferences = getApplicationContext().getSharedPreferences(login, Context.MODE_PRIVATE);    }    public static void writeLoginInfo(String name, String pass) {        sharedPreferences.edit().putString(name, name).putString(pass, pass).commit();    }    public static String getName() {        return sharedPreferences.getString(name, );    }}


 

At the same time, the notification is obtained in the onActivityResult method of JsActivity, and then the loginSuccess method of the H5 page is called and passed to the receiver of the H5 client.

 

@ Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {super. onActivityResult (requestCode, resultCode, data); if (requestCode = RESULT_ OK) {String name = App. getName (); name = TextUtils. isEmpty (name )? Not logged on: name; Log. d (TAG, onActivityResult: + name = + name); // call the loginSuccess method webview in H5 javascript. loadUrl (javascript: loginSuccess ('+ name + '));}}

 

 

Webview. loadUrl (javascript: loginSuccess ('+ name + '));

This is how the client calls javascript in H5.

 

function loginSuccess(name) {document.getElementById(loginName).value = name;}

The value Attribute assigned by name to the loginName control.

 

LoginSuccess: the javascript method in H5

Name: method parameter

 

 

Summary:

Use addJavascriprtInterface of webview (Operation object, javascript Object Name );

H5 call client method:

No return value: window. javascript Object. Client js method;

Return value: var value = window. javascript Object. Client js method;

The client calls the H5 method:

Webview. loadUrl (javascript: Method Name (parameter ));

Webview. loadUrl (javascript: Method Name ());

 

At this point, WebView and javascript methods have been called each other. I hope to help you and point out some shortcomings.

 

 

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.