2017-07-20 3 views
0

J'essaie de transmettre une valeur à partir d'un fichier javascript personnalisé que j'ai inclus après le chargement d'une URL dans un affichage Web.Impossible d'envoyer de la valeur à partir du fichier Javascript vers Android Activité

J'ai vérifié cette reference mais cela ne fonctionne pas lorsque je charge un site Web en dehors d'un fichier index.html local.

Voici mon code d'activité où j'ai créé le Javacript Interface:

public class MainActivity extends AppCompatActivity { 

    public static String URL = "https://www.ornativa.com"; 
    private WebView mWebView; 
    private RelativeLayout mLoader; 
    private Toolbar mToolbar; 
    JSInterface JSI = new JSInterface(this); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     createWebView(); 
    } 

    @SuppressLint("SetJavaScriptEnabled") 
    public void createWebView(){ 
     mWebView = (WebView)findViewById(
       R.id.webView); 
     mToolbar = (Toolbar)findViewById(R.id.toolbar); 

     mToolbar.setTitle(getResources().getString(R.string.app_name)+" | "+getResources().getString(R.string.app_name_hindi)); 
     mLoader = (RelativeLayout) findViewById(R.id.loader); 
     // Add javascript support to the webview 
     mWebView.getSettings().setJavaScriptEnabled(true); 
     // Enable pinch zoom controls on webview 
     mWebView.getSettings().setBuiltInZoomControls(false); 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
      if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)) 
      { WebView.setWebContentsDebuggingEnabled(true); } 
     } 
     // Add a WebViewClient 
     mWebView.setWebViewClient(new WebViewClient() { 

      @Override 
      public void onPageFinished(WebView view, String url) { 

       // Inject CSS when page is done loading 
       injectCSS(); 
       injectJS(); 
       super.onPageFinished(view, url); 
       mLoader.setVisibility(View.GONE); 
      } 
     }); 

     mWebView.addJavascriptInterface(JSI, "Android"); 

     // Load a webpage 
     mWebView.loadUrl(URL); 
    } 

    public void injectCSS(){ 
     try { 
      InputStream inputStream = getAssets().open("styles.css"); 
      byte[] buffer = new byte[inputStream.available()]; 
      inputStream.read(buffer); 
      inputStream.close(); 
      String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP); 
      mWebView.loadUrl("javascript:(function() {" + 
        "var parent = document.getElementsByTagName('head').item(0);" + 
        "var style = document.createElement('style');" + 
        "style.type = 'text/css';" + 
        // Tell the browser to BASE64-decode the string into your script !!! 
        "style.innerHTML = window.atob('" + encoded + "');" + 
        "parent.appendChild(style)" + 
        "})()"); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private void injectJS() { 
     try { 
      InputStream inputStream = getAssets().open("script.js"); 
      byte[] buffer = new byte[inputStream.available()]; 
      inputStream.read(buffer); 
      inputStream.close(); 
      String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP); 
      mWebView.loadUrl("javascript:(function() {" + 
        "var parent = document.getElementsByTagName('head').item(0);" + 
        "var script = document.createElement('script');" + 
        "script.type = 'text/javascript';" + 
        "script.innerHTML = window.atob('" + encoded + "');" + 
        "parent.appendChild(script)" + 
        "})()"); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onBackPressed() { 
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setCancelable(false); 
      builder.setIcon(R.mipmap.ic_launcher); 
      builder.setTitle(R.string.app_name); 
      builder.setMessage("Do you really want to Exit?"); 
      builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        //if user pressed "yes", then he is allowed to exit from application 
        finish(); 
       } 
      }); 
      builder.setNegativeButton("No", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        //if user select "No", just cancel this dialog and continue with app 
        dialog.cancel(); 
       } 
      }); 
      AlertDialog alert = builder.create(); 
      alert.show(); 

    } 
    public class JSInterface { 

     private Context mContext; 

     public JSInterface(Context c) { 
      mContext = c; 

     } 
     @JavascriptInterface 
     public void showToast(String message) { 
      Toast.makeText(mContext, message, Toast.LENGTH_LONG).show(); 
     } 

    } 


} 

Et ceci est mon fichier script.js:

document.getElementById("aadhaarNo").type= 'tel'; 
var myElem = document.getElementById('actionMessages'); 
Android.showToast("Hello World!"); 
if (myElem === null) { 
    console.log('does not exist'); 
} 
else{ 
    if (myElem.classList.contains('success')){ 
     console.log('success'); 
    } 
} 

Je suis en train d'appeler la fonction à partir du script fichier pour envoyer la valeur au Toast, mais le Toast n'apparaît pas.

Répondre

1

Remplacez "Contexte" par "Activité" dans la classe JSInterface. Vérifiez le code ci-dessous.

public class JSInterface { 

     private Activity mContext; 

     public JSInterface(Activity c) { 
      mContext = c; 

     } 

     @JavascriptInterface 
     public void showToast(String message) { 
      Toast.makeText(mContext, message, Toast.LENGTH_LONG).show(); 
     } 

    }