6

In my application I am using webView to call a URL. My website is using web Socket to change values. when i open same URL in chrome application it's value changes it means web socket is working fine. But, inside webView value change is not happening. Is it mean web Socket is not supporting in webView widget. Where, I have noticed that WebViewClient's onLoadResource() method keeps calling infinite times.

hannna patait
  • 355
  • 2
  • 11

3 Answers3

12

Web socket did not work because local storage is disabled by default.

Enabling it in my Android WebView solved the issue.

webView.getSettings().setDomStorageEnabled(true);
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
hannna patait
  • 355
  • 2
  • 11
  • Hi, so does this mean websocket is working normally in your webview app now? I ask because in the older question (https://stackoverflow.com/questions/13507438/websocket-in-android-webview) on this topic, the accepted answer says it is not supported. So I want to be sure before starting. Thanks! – ahron Mar 19 '21 at 01:44
0

For my case, I had to enable AppCache as well. It working fine now.

final WebSettings settings = web.getSettings();

    settings.setLoadsImagesAutomatically(true);
    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);
    settings.setAppCacheEnabled(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        settings.setSafeBrowsingEnabled(false);
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }
    web.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(web, true);
    }


    // Extras tried for Android 9.0, can be removed if want.
    settings.setAllowContentAccess(true);
    settings.setAllowFileAccess(true);
    settings.setBlockNetworkImage(false);
Harpreet
  • 2,990
  • 3
  • 38
  • 52
0

Check your error code first; if the code is: ERR_CLEARTEXT_NOT_PERMITTED try to add this to your application tag in your AndroidManifest.xml like below:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:theme="@style/AppTheme"
    android:usesCleartextTraffic="true">
Alessio
  • 3,404
  • 19
  • 35
  • 48
Kaeson
  • 11
  • 1
  • Hi, after doing this, does websocket work on webview apps? The older answers say it is not supported, so I am a little confused. – ahron Mar 19 '21 at 01:46