Android - 如何在Android WebView中使用Javascript? [英] Android - How to use Javascript in an Android WebView?

查看:97
本文介绍了Android - 如何在Android WebView中使用Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的混合Android应用程序中存在问题。我需要一个带有HTML的WebView,在这个HTML中我有一个按钮。

I have a problem in my Hybrid Android App.I need to have a WebView with an HTML and in this HTML I have a button.

我有一个带有WebView的布局,我在HTML中有一个按钮,我正在尝试用另一个屏幕启动第二个Activity(也是一个带有WebView的布局)当用户点击此按钮时。

I have a layout with a WebView and I have a button inside the HTML, I'm trying to launch a second Activity with another screen(also a layout with a WebView) when the user click this button.

我的问题是这个按钮没有启动第二个活动。

My problem is that this button is not launching the second activity.

我正在使用Cordova。

I'm using Cordova.

这是我的布局( pruebas.xml ):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/textView" />

</LinearLayout>

这是我的 MainActivity.java

public class MainActivity extends CordovaActivity{

    WebView wv;

    JavaScriptInterface JSInterface;

    @Override
    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

        setContentView(R.layout.pruebas);
        wv = (WebView)findViewById(R.id.webview);

        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setDomStorageEnabled(true);
        // register class containing methods to be exposed to JavaScript

        JSInterface = new MainActivity.JavaScriptInterface(this);
        wv.addJavascriptInterface(JSInterface, "JSInterface");

        wv.loadUrl("file:///android_asset/www/description.html");

    }

    public class JavaScriptInterface {
        Context mContext;

        /** Instantiate the interface and set the context */
        JavaScriptInterface(Context c) {
            mContext = c;
        }

        @android.webkit.JavascriptInterface
        public void changeActivity(){
            Intent i = new Intent(MainActivity.this, JavascriptInterfaceActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
            finish();
        }
    }
}

这是我的第二项活动( JavascriptInterfaceActivity.java ):

And this is my second activity (JavascriptInterfaceActivity.java):

public class JavascriptInterfaceActivity extends Activity {

    WebView wv;

    JavaScriptInterface JSInterface;

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

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

        setContentView(R.layout.pruebas);
        wv = (WebView)findViewById(R.id.webview);

        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setDomStorageEnabled(true);

        JSInterface = new JavaScriptInterface(this);
        wv.addJavascriptInterface(JSInterface, "JSInterface");

        wv.loadUrl("file:///android_asset/www/description-long.html");

    }


    public class JavaScriptInterface {
        Context mContext;

        /** Instantiate the interface and set the context */
        JavaScriptInterface(Context c) {
            mContext = c;
        }

        @android.webkit.JavascriptInterface
        public void changeActivity(){
            Intent i = new Intent(JavascriptInterfaceActivity.this, MainActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
            finish();
        }
    }
}

这是 description.html ,其他HTML( description-long.html )类似:

This is the description.html, the other HTML (description-long.html) is similar:

<!DOCTYPE html>
<html>
<head>
    <script src='changeactivity.js'></script>

    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <title>Main activity</title>
</head>
<body>
<button id='changeactivity'>Changue activity</button>
</body>
</html>

这是我的 changeactivity.js 文件 assets / www

 function displaymessage(){
     JSInterface.changeActivity();
 }

 document.addEventListener('DOMContentReady', function () {
         document.getElementById('changeactivity').addEventListener('click', displaymessage);
 });

有任何建议吗?我查看这些帖子:

Any suggestion? I check these posts:

https://stackoverflow.com/a/ 10481108/3739382

https://stackoverflow.com/ a / 31631068/3739382

推荐答案

基于绑定JavaScript文档


注意:绑定到JavaScript的对象在另一个线程中运行,而不是在构造它的线程中运行。

Note: The object that is bound to your JavaScript runs in another thread and not in the thread in which it was constructed.

您正在非UI线程上启动活动。您应该在UI线程上运行它,如下所示:

You are starting the activity on non-UI thread. You should run it on UI thread as follows:

@android.webkit.JavascriptInterface
    public void changeActivity(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                 Intent i = new Intent(MainActivity.this, JavascriptInterfaceActivity.class);
                 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                 startActivity(i);
                 finish();
            }
        });

    }

或者你也可以使用Handler。

Alternatively you can also use Handler.

这篇关于Android - 如何在Android WebView中使用Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆