Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript not reloading in Android webview?

I have made a simple webview application that pulls this HTML page that uses PHP and JavaScript: http://s-ka-paidbeats.com/app_tree/randomword/5.html

The problem is that the JavaScript is not refreshing on my mobile device and I can't figure out why!

When I test the page on my desktop web browser it works fine sometimes but the page just never refreshes and the words stay the same. On my Android phone the word do not update or refresh at all and I can't figure out why this is happening.

Here is the actual page users view (the 5.html file):

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <script type="text/JavaScript">
      function timedRefresh(timeoutPeriod) {
        setTimeout("location.reload(true);",timeoutPeriod);
      }
      window.onload = timedRefresh(7000);
    </script>
    <title>Freestyle Word Generator - 5 Seconds</title>
    <style type="text/css">
      body, td, p, input {
        color : #000000;
        font-family: Impact, Haettenschweiler, 'Franklin Gothic Bold', Charcoal, 'Helvetica Inserat', 'Bitstream Vera Sans Bold', 'Arial Black', 'sans serif';
        font-size : 12px;
      }
      .button {
        background-color: #f44336;
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
      } /* Red */ 
    </style>
    <link rel="stylesheet" href="app1.css">
  </head>
  <body style="background-color:#000000;text-align:center;color:#fff">
    <div class="w3-container w3-orange">
      <h1 style="text-align: center;margin:0px;margin-top:15px;font-family: Impact, Haettenschweiler, 'Franklin Gothic Bold', Charcoal, 'Helvetica Inserat', 'Bitstream Vera Sans Bold', 'Arial Black', 'sans serif';">Freestyle Word Generator</h1>
      <p style="text-align:center;margin:0px;margin-bottom:15px;font-family: Impact, Haettenschweiler, 'Franklin Gothic Bold', Charcoal, 'Helvetica Inserat', 'Bitstream Vera Sans Bold', 'Arial Black', 'sans serif';font-size : 16px;">Sharpen Your Skills!</p>
    </div>
    <p style="color:#ff9800;font-size:30px;margin-bottom:0px;">YOUR WORD IS:</p>
    <p style="color:#fff;font-size : 30px;margin-top:5px;"><script type="text/javascript" src="randomword.php?type=1"></script></p>
    <script>
      function startTimer(duration, display) {
      var timer = duration, minutes, seconds;
      setInterval(function () {
          minutes = parseInt(timer / 60, 10)
          seconds = parseInt(timer % 60, 10);

          minutes = minutes < 10 ? "0" + minutes : minutes;
          seconds = seconds < 10 ? "0" + seconds : seconds;

          display.textContent = minutes + ":" + seconds;

          if (--timer < 0) {
              timer = duration;
          }
      }, 1000);
      }
      window.onload = function () {
      var fiveMinutes = 5 * 1,
          display = document.querySelector('#time');
      startTimer(fiveMinutes, display);
      };
    </script>
    <div style="color:#555;">New Word In <span id="time">00:05</span> Seconds!</div>
    <br><br>
    <input type="button" style="background-color: #ff9800;border: none;color: black;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 20px;" onclick="location.href='http://s-ka-paidbeats.com/app_tree/randomword/index.php';" value="STOP" />
  </body>
</html>

Here is my Android class data:

package com.randomword.app.randomword;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.randomword.app.randomword.NetorkConnection;
@SuppressLint("SetJavaScriptEnabled")
public class Beats extends AppCompatActivity {

private WebView webView;
NetorkConnection ntwrk_con = new NetorkConnection(this);
ProgressDialog dialog;


public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    TextView toolsresources5 = (TextView)findViewById(R.id.feedbacktextview);
    toolsresources5.setVisibility(View.INVISIBLE);





    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    webView = (WebView) findViewById(R.id.activity_main_webview);



    dialog = new ProgressDialog(Beats.this);


    if (ntwrk_con.isConnectingToInternet()) {

        webView();

    } else {
        dialog_box_for_internet();
    }

}

public void dialog_box_for_internet() {
    if (ntwrk_con.isConnectingToInternet()) {

        webView();

    } else {
        // dismis_dialog_box_for_internet = true;
        AlertDialog.Builder builder = new AlertDialog.Builder(
                Beats.this);
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_custom_titile, null);
        TextView title = (TextView) view.findViewById(R.id.myTitle);
        title.setText("Unable To Connect");
        builder.setCustomTitle(view);
        builder.setMessage("No Internet Connection")
                .setCancelable(false)
                .setPositiveButton("Retry",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                if (ntwrk_con.isConnectingToInternet()) {

                                    webView();

                                } else {
                                    new Thread_for_internet().execute();
                                }
                                // dialog.cancel();
                            }
                        })
                .setNegativeButton("Okay",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                finish();

                                // Gridview.super.onBackPressed();
                            }
                        });

        AlertDialog alert = builder.create();
        alert.show();
    }
}

class Thread_for_internet extends AsyncTask<String, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setMessage("Loading..Please wait.");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

    }

    @Override
    protected Boolean doInBackground(String... args) {

        try {

            Thread.sleep(2000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    protected void onPostExecute(Boolean result) {
        dialog.dismiss();
        dialog_box_for_internet();

    }

}

public void webView() {
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    });
    dialog.setMessage("Picking Yes Or No...\nOne Moment...");
    dialog.setCanceledOnTouchOutside(false);
    dialog.show();

    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.getSettings().setLoadsImagesAutomatically(true);
    webView.setWebChromeClient(new WebChromeClient());


    webView.loadUrl("http://s-ka-paidbeats.com/app_tree/randomword/5.php?nocache=1");

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setLoadsImagesAutomatically(true);


}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    boolean bRet=false;//set true is menu selection handled
    switch (item.getItemId()) {
        case R.id.action_settings_3:
            Toast.makeText(this, Html.fromHtml("<big><b>Develeped By S-Ka-Paid</b></big><br>© 2016 S-Ka-Paid"), Toast.LENGTH_LONG).show();
            bRet=true;
            break;
        case R.id.action_settings_4:
            Intent intent2 = new Intent(Intent.ACTION_VIEW);
            //Try Google play
            intent2.setData(Uri.parse("market://details?id=com.yesorno.app.yesorno"));
            startActivity(intent2);
            bRet=true;
            break;
        default:
            bRet=super.onOptionsItemSelected(item);
    }
    return bRet;
}
}

If you visit the page: http://s-ka-paidbeats.com/app_tree/randomword/5.php on a desktop sometimes it works and sometimes the browser will not change the random word after the first word..... I'm thinking it has something to do with browser caching or something I'm not sure.

like image 594
skapaid Avatar asked Mar 25 '16 23:03

skapaid


People also ask

How to enable JavaScript in Android WebView?

JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView . You can retrieve WebSettings with getSettings() , then enable JavaScript with setJavaScriptEnabled() . WebView myWebView = (WebView) findViewById(R.

How to embed WebView in Android?

To add a WebView to your app, you can either include the <WebView> element in your activity layout, or set the entire Activity window as a WebView in onCreate() .

How to set WebView in Android?

Modify src/MainActivity. java file to add WebView code. Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified main activity file src/MainActivity.

How WebView works in Android?

Android WebView is used to display web page in android. The web page can be loaded from same application or URL. It is used to display online content in android activity. Android WebView uses webkit engine to display web page.


1 Answers

I've run in the same problem location.reload();is ignored by the WebView.

The idea was to call, from the Android Activity, webview.reload() and trigger this call from Javascript using @JavascriptInterface.

This lead to other problems but I've found a workaround with AsyncTask as explained here: Unable to reload Android WebView from Javascript

like image 86
Punkman Avatar answered Sep 23 '22 14:09

Punkman