将JavaScript变量传递给Android活动? [英] Passing a Javascript Variable to Android Activity?

查看:81
本文介绍了将JavaScript变量传递给Android活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想获取我已经从javascript访问过的数据并将它传递给Java / Android,以便我可以在那里使用它。

  / *这个类的一个实例将被注册为一个JavaScript接口* / 
class MyJavaScriptInterface {


@SuppressWarnings(unused)
public void setX(String html){
Activity.this.x = html;
Toast.makeText(myApp,Activity.this.x,Toast.LENGTH_LONG).show();
}

}

这有效,但我想成为能够在任何地方调用相同的Toast线并获得相同的结果。目前只有当通过webview.loadUrl(Javascript:...



加载没有调用时才返回null / empty。


你不能访问存储的javascript变量,你必须通过函数调用来完成
你必须在你的html页面中从javascript调用它,例如:

  TheNameOfYourInterface.setX('value'); 

通过

 <$将接口添加到webview中时,NameOfYourInterface将会是一个JavaScript对象c $ c> YourWebView.addJavascriptInterface(new MyJavaScriptInterface(),TheNameOfYourInterface); 

所以你可以在你的webview上做逻辑并在设置数据时调用接口,以便调用Java方法。


Basically I want get data I already have accessed from javascript and passing it to Java/Android so that I can work with it there.

     /* An instance of this class will be registered as a JavaScript interface */
    class MyJavaScriptInterface {


        @SuppressWarnings("unused")
        public void setX(String html){
            Activity.this.x = html;
            Toast.makeText(myApp, Activity.this.x, Toast.LENGTH_LONG).show();
        }

    }

this works but I want to be able to call the same Toast line anywhere and get the same result. Currently it only returns null/empty when not called through loading through webview.loadUrl("Javascript:"...

Any tips?

解决方案

You can not access stored javascript variables, you must do it through a function call. You have to call it from javascript in your html page, for example:

TheNameOfYourInterface.setX('value');

TheNameOfYourInterface will be a javascript object when you add the interface to the webview via

YourWebView.addJavascriptInterface(new MyJavaScriptInterface(),"TheNameOfYourInterface");

so you can do the logic on your webview and call the interface when you set the data so the method in the Java side will be called.

这篇关于将JavaScript变量传递给Android活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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