乐闻世界logo
搜索文章和话题

How to debug javascript in webview in android

1个答案

1

Debugging JavaScript code in WebView on Android can be done in several ways:

1. Using Chrome's Remote Debugging Feature (Remote Debugging)

Starting from Android 4.4 (KitKat), developers can use Chrome browser's remote debugging feature to debug JavaScript code within WebView. To use this method, follow these steps:

  • Ensure your device is connected to your development machine via USB with USB debugging enabled. You can enable USB debugging in the device's Developer Options.

  • In your application, ensure WebView is enabled for debugging. Add the following code in your Application class or the onCreate method of your starting Activity:

    java
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); }
  • Open your Chrome browser and enter chrome://inspect in the address bar and press Enter.

  • You should see an option named 'Discover USB devices'; ensure it is checked.

  • On the page, locate your device and the corresponding WebView. Click the 'inspect' link to open a developer tools window.

  • In the opened developer tools, you can view elements, console output, network requests, etc., just like debugging a webpage in Chrome browser.

2. Output Logs

Use console.log in JavaScript code to print debugging information, and view the output in Android's LogCat. To capture console.log output from WebView, you need to set a WebChromeClient and override the onConsoleMessage method:

java
webView.setWebChromeClient(new WebChromeClient() { public boolean onConsoleMessage(ConsoleMessage cm) { Log.d("MyApplication", cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId() ); return true; } });

This will make all console.log outputs visible in Android's LogCat.

3. Using JavaScript Interface

For more complex interactions, you can create a JavaScript interface in Android to allow JavaScript code to call native Android code:

java
public class WebAppInterface { Context mContext; /** Instantiate the interface and set the context */ WebAppInterface(Context c) { mContext = c; } /** Show a toast from the web page */ @JavascriptInterface public void showToast(String toast) { Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); } } // Add this when setting up WebView webView.addJavascriptInterface(new WebAppInterface(this), "Android");

Then call it from JavaScript like this:

javascript
Android.showToast("Hello Android!");

This method can be used for creating complex debugging or interactions, but be mindful of security issues; ensure JavaScript interfaces are only used on trusted content.

By using the above methods, you can debug JavaScript code in WebView during Android app development. Remember to disable WebView's debugging mode before releasing your app to avoid security risks.

2024年6月29日 12:07 回复

你的答案