我正在尝试使用带有输入框的webview,获取字符串,并将其传递给第二个活动.由于某种原因,该按钮没有做任何事情,我收到错误:
未捕获的TypeError:对象[object Object]在file:///android_asset/www/index.js上没有方法'changeActivity':3
所以我的HTML说:
我的JS说:
function checkMovie() { var movieName = document.getElementById('name').value; webapi.changeActivity(movieName);}
我的Android代码说:
public class MainActivity extends Activity implements OnClickListener { // Setting up known variables JavaScriptInterface JSInterface; Button find; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // changing main layout to show the splash first setContentView(R.layout.activity_main); // Tie my webviews and set up the webview to handle JS WebView webView = (WebView) findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); // Expecting UI webView.setWebChromeClient(new WebChromeClient()); // allowing to inject Java objects into a page's JavaScript webView.addJavascriptInterface(new JavaScriptInterface(this), "webapi"); // Load the local file webView.loadUrl("file:///android_asset/www/index.html"); find = new Button(MainActivity.this); find.setOnClickListener(this); WebSettings ws = webView.getSettings(); ws.setJavaScriptEnabled(true); // Add the interface to record javascript events webView.addJavascriptInterface(find, "find"); } public class JavaScriptInterface { Context mContext; // Instantiate the interface and set the context JavaScriptInterface(Context c) { mContext = c; } // Call the function changeActivity defined in my JS of my HTML public void changeActivity(String movieName) { // Call the Movie App and store the intent to pass it onto the app. Log.e("XXXXXXXXXXXXXXX", "X==========>" + movieName); Intent i = new Intent(MainActivity.this, second.class); i.putExtra("movie_name", movieName); startActivity(i); } } @Override public void onClick(View v) { // TODO Auto-generated method stub if (v.equals(find)) { Log.e("XXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXX"); } }
}
问题正是如此.由于您运行4.2.2,您必须在您的changeActivity方法和您在Android代码中调用的任何其他JavaScript方法上设置@JavascriptInterface注释.
@JavascriptInterface public void changeActivity(String movieName) { ...
这对于Android 4.2或更高版本是必需的.
请点击此链接阅读更多内容.
首先在Android 4.2及更高版本上,确保添加了@JavascriptInterface注释.
然后,如果你发现它在发布(生产)模式下停止工作,那是因为proguard
.
# If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: # -keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #}