2017-07-20 51 views
0

我想從我在webview中加載URL後包含的自定義JavaScript文件傳遞一個值。無法將Javascript文件中的值發送到Android活動

我已經檢查了這個reference,但是當我從一個本地index.html文件中加載一個網站時它不起作用。

這裏就是我創建了Javacript接口我的活動代碼:

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(); 
     } 

    } 


} 

,這是我的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'); 
    } 
} 

我試圖從腳本調用函數文件將值發送到Toast,但Toast不會出現。

回答

1

將「Context」更改爲類JSInterface中的「Activity」。檢查下面編輯的代碼..

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(); 
     } 

    } 
相關問題