Currently I'm trying to figured out which is the best way to invoke javascript from android.
AndroidJSCore. AndroidJSCore
WebView
I've tried AndroidJSCore, it's great. But it would enlarge the apk size.
Then I trying to dive into WebView to invoke javascript. But fail.
Activity look like this:
public class WebViewActivity extends AppCompatActivity {
private WebView webView;
private static final String TAG = WebViewActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView)findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportZoom(true);
webSettings.setDisplayZoomControls(true);
webView.loadUrl("file:///android_asset/jsWeb/test.html");
webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
String test1 = "permissionRegist(\"'function'\", [\"'319609831167500021'\",\"'319609831167500022'\",\"'319609831167500023'\",\"'419609839767500020'\",\"'644731700926740003'\",\"'644731700926740004'\",\"'854885785357389824'\",\"'854995673156816896'\",\"'855001385022918656'\",\"'855009454683459584'\",\"'855298661779902464'\",\"'855303143108513792'\",\"'855347061611171840'\",\"'855356859882803200'\"])";
String test2 = "evalJSExpression()";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript(test1, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.d(TAG, s);
}
});
webView.evaluateJavascript(test2, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.d(TAG, s);
}
});
}
}
});
}
}
there appending files are:
android.js
function permissionRegist(type, list) {
var s_permissionMap = new Map();
s_permissionMap.set(type, list);
}
function evalJSExpression() {
var result = 'dddddd';
return result;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LogicalExpression</title>
<!-- 导入script -->
<script type="text/javascript" src="android.js"></script>
</head>
<body>
<!--<button onClick="permissionRegist()">点击读取文件</button>-->
</body>
</html>
but the result is :
I/chromium: [INFO:CONSOLE(2)] "Uncaught ReferenceError: Map is not defined", source: file:///android_asset/jsWeb/android.js (2)
D/WebViewActivity: null
D/WebViewActivity: "dddddd"
Have you tried https://github.com/mozilla/rhino
here is an example : http://lifeofcoding.com/2015/04/05/Execute-JavaScript-in-Android-without-WebView/
AndroidJSCore is a great lib for android to invoke javascript without WebView.
It seems that Both Native WebView and rhino might have some compilable issues due to the different versions of javascript.
Welcome to contact me about this.
I would find out why when I have time.
Related
I have a simple web-app, Html page with a simple javascript script in it and an android app that has a webview in it to show the html page and i need to call the android methods from the javascript.
However it works with showToast() when i click on a button in the html
How can i call this speak() method from android in the js code??
public class WebAppInterface {
public MainActivity mainActivity;
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();
}
/**
* Start the speechToText from the web page
* */
#JavascriptInterface
public void startSpeak(){
mainActivity.speak();
}
}
Here is the speech to text code:
private void speak() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Say something");
try{
startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT);
}
catch (Exception e){
Toast.makeText(this,""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case REQUEST_CODE_SPEECH_INPUT:{
if(resultCode == RESULT_OK && null!=data){
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mTextTv.setText(result.get(0));
}
break;
}
}
}
Here is the html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
</div>
<hr>
<hr>
<div>
<input type="button" value="Record" onClick="speak()" />
</div>
<div>
<h1>Here goes the generated text:</h1>
<p id="toText"> genText </p>
</div>
<script type="text/javascript">
var genText = 'testing now'
genText = Android.getTextGen();
function speak() {
Android.showToast("start Recording")
Android.startSpeak();
}
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
</body>
</html>
Below I attached the code to be executed with webview.
NOTE: JAVASCRIPT SHOULD BE ENABLED
ANYONE HELP ME TO RUN THIS HTML STRING IN WEBVIEW
<!DOCTYPE html>
<html>
<body>
<!-- Markup for HTML (Factors in Placement and Enrollment of Primary
Care Patientsin YMCA's Diabetes Prevention Program, Bronx, New
York,2010-2015) --><div class='rid_08184eef_309335'
data-apiroot='//tools.cdc.gov/api' data-mediatype='html'
data-mediaid='309335' data-stripscripts='true' data-stripanchors='false'
data-stripimages='false' data-stripcomments='true'
data-stripstyles='true' data-cssclasses='syndicate' data-ids=''
data-xpath='' data-oe='utf-8' data-of='xhtml' data-ns='cdc'
data-postprocess='' data-nw='true' data-iframe='true'
data-cdc-widget='syndicationIframe'
data-apiembedsrc='skins/larry//tools.cdc.gov/api/embed/html/js/embed-2.0.3.js'
data-iframeembedsrc='skins/larry//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js'></div><script
src='skins/larry//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js'
></script><noscript>You need javascript enabled to view this content or go to <a href='skins/larry//tools.cdc.gov/api/v2/resources/media/309335/noscript'>source URL</a>.</noscript>
</body>
</html>
I followed this link for basic setup. Nothing helped
BELOW I ATTACHED MY JAVA CODE
public class WebtestActivity extends Activity {
WebView webtest;
final Activity activity = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.webviewtesting);
webtest=(WebView)findViewById(R.id.webtest);
String htmlString = "<!-- Markup for HTML (How to Prevent Cancer or Find It Early) --><div class=\"rid_ec9fb40c_123238\" data-apiroot=\"//tools.cdc.gov/api\" data-mediatype=\"HTML\" data-mediaid=\"123238\" data-stripscripts=\"false\" data-stripanchors=\"false\" data-stripimages=\"false\" data-stripcomments=\"false\" data-stripstyles=\"false\" data-cssclasses=\"syndicate\" data-ids=\"\" data-xpath=\"\" data-oe=\"UTF-8\" data-of=\"XHTML\" data-ns=\"\" data-postprocess=\"\" data-nw=\"true\" data-iframe=\"true\" data-cdc-widget=\"syndicationIframe\" data-apiembedsrc=\"//tools.cdc.gov/api/embed/html/js/embed-2.0.3.js\" data-iframeembedsrc=\"//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js\" data-font=\"\"></div><script src='//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js' ></script><noscript>You need javascript enabled to view this content or go to <a href='//tools.cdc.gov/api/v2/resources/media/123238/noscript'>source URL</a>.</noscript>";
webtest.getSettings().setJavaScriptEnabled(true);
webtest.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webtest.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
Log.d("des===",description);
Log.d("failingUrl===",failingUrl);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
Log.d("shouldlLoading===",url);
view.loadUrl(url);
return true;
}
});
webtest.loadData(htmlString, "text/html", null);
}
}
try this code. If you are learning, use official docs > WebView
String htmlString = "<html><body>Your text.</body></html>";
browser.getSettings().setJavaScriptEnabled(true);
browser.loadData(htmlString, "text/html", null);
Your code working fine. I attached screenshot
I'm using cordova/phonegap to make a Android app and trying to call JavaScript funtion from android/native
My main acitvity:-
public class MainActivity extends CordovaActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
loadUrl(Url);
// TODO call javascripte from here
}
}
My index.html page
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8">
function myFun(){
alert("call from the ANDROID");
}
</script>
</head>
<body >
</body>
</html>
I want call JavaScript function from phonegap.
try this code
webView.loadUrl("javascript:myFun()");
I am using webview to render html file and i used java script to highlight (Hello) word in html
public class MyActivity extends Activity{
WebView myWebView;
TextView myResult;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myResult = (TextView)this.findViewById(R.id.myResult);
myWebView = (WebView)this.findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
String txt="Hello";
myWebView.loadUrl("javascript:var text='"+ txt+ "';if (window.find) {document.designMode ='on';var sel = window.getSelection();sel.collapse(document.body, 0);while (window.find(text)) { document.execCommand('HiliteColor', false, 'red');sel.collapseToEnd();}document.designMode = 'off';} else if (document.body.createTextRange) { var textRange = document.body.createTextRange(); while (textRange.findText(text)) {textRange.execCommand('BackColor', false, 'red'); textRange.collapse(false);}}");
myWebView.addJavascriptInterface(new JavaScriptHandler(this), "MyHandler");
}
and this my html
<html>
<head>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
this code is run good in debug mode i mean that it already highlight (hello) but in running mode it did not why???????????
i do not know what it mean that running good in debug mode but not in running mode?
I want to create a button in html and make a call from that button from android through javascript. I have written the following code , which is not working :
I am beginner for android.
public class MainActivity extends Activity {
private static final String PIC_WIDTH = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new JsInterface(), "android");
myWebView.loadUrl("file:///android_asset/www/index.html");
}
public class JsInterface{
public void makeCall()
{
Log.i("Myactivity","inside android makecall");
// Here call any of the public activity methods....
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9611396958"));
startActivity(callIntent);
}
}
}
in javascript :
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body class="bgClass" id="body" ontouchstart="">
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script src="js/myScript.js"></script>
<button id="makeCall" >CALL</button>
<script>
$("#makeCall").click(function(){
console.log("inside click javascript");
console.log(window.android);
android.makeCall();
});
</script>
</body>
</html>
any help??
Make sure your $("#makeCall") method is responding in html.
Then make below changes.It will work.
public class JsInterface{
#JavascriptInterface
public void makeCall()
{
Log.i("Myactivity","inside android makecall");
// Here call any of the public activity methods....
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9611396958"));
startActivity(callIntent);
}
}
This annotation allows exposing methods to JavaScript.
I am answering my own question so that it can help others .:)
Finally solved it :
myWebView.setWebViewClient(new MyAppWebViewClient()); it was missing so javascript was not working . And i must add #JavascriptInterface as Hardik Trivedi suggested above.
It is working fine now.
simply adding webView.getSettings().setJavaScriptEnabled(true); worked for me.
must add #JavascriptInterface too.