How to call javascript method when loading Android - javascript

I'm a beginner at android.
I used javascript method in android. And I want to call it when the app is loaded for first time.
For example,
testMethod = function(str) {
alert("hi" + str);
}//javascript
and
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDefaultTextEncodingName("utf-8");
mWebView.loadUrl("file:///index.html");
mWebView.addJavascriptInterface(androidBridge, "jsinterface");
mWebView.loadUrl("javascript:testMethod('javascript')");
}
What I was thinking here is the alert will pop up immediately when I start the app.
But nothing happens.
About this, I have two questions.
1.Can I call and use the javascript method in Android's onCreate method?
2.If it is possible, How can I do?

if you want to show a popup on start just use the default AlertDialog. see the code below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showMessage("My Message Here", "Title here");
}
private void showMessage(String data, String title){
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(data)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue
}
})
.show();
}

check out whether index.html is REALLY loaded. I guess that webview didn't load your html properly, bcz it's not an invalid file path. try file:///mnt/sdcard/index.html. (or something likely)
try to put mWebView.loadUrl("javascript:testMethod('javascript')") in view.post or view.postDelayed.

Related

how to hide some dom element in html code of webpage in android?

i have spent much time looking for the solution of this problem but i coundn't find it at all. i tried the following code but it doesn't seem to work so plese help me out......
public class MainActivity extends AppCompatActivity {
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:(function() {document.getElementById('header')[0].style.display='none';})()");
}
});
webView.loadUrl(url);
}
}
An ID(header) should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element.
So use
document.getElementById('header').style.display='none';
instead of
document.getElementById('header')[0].style.display='none';

How can I request to open an URL without opening the webbrowser?

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
//Do anything with result here :D
Log.w("handleResult", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan result");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(result.getText().toString()));
startActivity(browserIntent);
mScannerView.resumeCameraPreview(this);
}
}
I want to directly open the URL once scanning is done and then reopen the camera. Can anyone please help me ?
Use a webview load the URL like below:
webView= (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
Try and create your own activity to handle request to open URL .
When I started learning about android and its intents I found it very confusing. But category BROWSABLE in the Manifest does the following.
The target activity can be safely invoked by the browser to display data referenced by a link — for example, an image or an e-mail message.
Read more on: http://developer.android.com/guide/components/intents-filters.html
The two other answers opens the standard web browser and goes to the address specified. If you want a custom browser make the second activity like a web view like this example.

Calling Java method in Android from JavaScript using webview

I'm trying to access my Java method helloWorld(); using JavaScriptInterface in Android, from the page I'm viewing using WebView
I'm a little new to this, and I don't know why I'm not getting the value to my html page
This is the Android code I'm using:
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web = (WebView) findViewById(R.id.webview01);
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
web.getSettings().setJavaScriptEnabled(true);
web.addJavascriptInterface(jsInterface, "JSInterface");
web.getSettings().setUseWideViewPort(true);
web.getSettings().setLoadWithOverviewMode(true);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://exampleweb:10110/exWeb/deposits.jsp");
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activity) {
this.activity = activity;
}
#JavascriptInterface
public String helloWorld(){
return("hello world");
}
}
}
This is the JavaScript code I've been using (on the page I'm viewing with WebView)
HTML button
<td> <button type="button" class="btn btn-xs btn-primary connectToAndroid">Test android</button></td>
JavaScript
$(".connectToAndroid").on('click', function () {
var val = window.JSInterface.helloWorld();
alert(val);
});
Does anyone know what I'm doing wrong here? I just want to alert an "Hello World" from android in my HTML page.
Any pointers are greatly appreciated!
Try by adding this line of code before loading the url and make sure you reference your jQuery library in the html.
web.setWebChromeClient(new WebChromeClient(this));
This is very weird, I tried using this a couple of hours ago:
$(".connectToAndroid").on('click', function () {
var val = Android.helloWorld();
alert(val);
});
Then I changed it, it didn't say Android anymore,
yet I kept getting an error saying:
Uncaught ReferenceError: Android is not defined
And after a while I figured, Android.helloWorld(); must be cached somehow in my webview app or something.
So, I changed back to this:
$(".connectToAndroid").on('click', function () {
var val = Android.helloWorld();
alert(val);
});
And added this:
web.addJavascriptInterface(jsInterface, "Android");
And now it works like a charm, as it should have from the beginning if it wasn't for some cache somewhere,
Can anyone explain why this happens? Does android webview actually cache javascript code? And can I prevent this behaviour in the future somehow? Cache bothers a lot when coding/testing new stuff.

webView loadURL not working on HTML button click

I have a webView in my application. The webView initially opens an HTML page I created with a few buttons on it. The buttons do various tasks (I'm trying to learn how to use webViews) like: 1)show android toast, 2)show javascript alert, 3)vibrate phone, 4)show current geolocation, 5)open google maps in webView.
It's this last one that's not working. I've searched this site and many others, but haven't found a solution that works.
I'm fairly certain I have all the manifest file 'stuff' correct (everything else is working, including the initial internet based web page). I'm happy to post that too though if you think it's needed.
My activity_main.xml file has never given me issues, but again, I'm happy to post that if you think it'll help.
Here are snippets from my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl(url); // this one works
myWebView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setGeolocationEnabled(true);
...
}
That all works and again the other html buttons work.
Then there's this:
public class WebAppInterface {
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();
}
#JavascriptInterface
public void vibrateDevice() {
Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
mVibrator.vibrate(500);
}
#JavascriptInterface
public void showMapCurPos() {
new Handler().post(new Runnable() {
String url2 = "http://www.google.com/maps/#53.001153,-95.0752916,15z";
#Override
public void run() {
myWebView.clearCache(true);//Here you call the methond in UI thread
myWebView.loadUrl(url2);
}
});
}
}
Everything works there, except for showMapCurPos(). I've already tried just a simple myWebView.loadUrl(...) along with several attempts at intents. Depending on what I've tried, sometimes that method crashes the app, but most of the time the new URL just doesn't get displayed and it stays on the original URL.
Please forgive me if this is a repeat question, but I really have searched this site and many others for an answer (probably for a solid 8 hours or so). I've tried many of those answers to no avail. I'm guessing it's something simple and has to do with my lack of understanding of webViews or activities or intents or all three or maybe even my newness to android development.
I can't write a comment yet, so I'm writing this as an answer.
You could try this answer:
myWebView.post(new Runnable() {...});
instead of using new Handler

Calling JavascriptInterface method through the WebView and JS function after changing config often doesnt work

I have some problem with calling a JavaScript function in a WebView and getting response in the app (on my Galaxy Tab 2 '10). I call the js-function directly after content loading. According this one solution i use a PictureListener
webView.setPictureListener(new PictureListener() {
#Override
public void onNewPicture(WebView view, Picture picture) {
webView.loadUrl("javascript: JsImpl.init('{response}');");
}
});
it works fine: when content is loaded, onNewPicture always is started.
"javascript: JsImpl.init('{response}') loads js that calls:
class JsImpl {
private final static String LOG_TAG = "JsImpl";
#JavascriptInterface
public void init(String json) {
Log.d(LOG_TAG, json);
}
}
In the log i see D/JsImpl(18400): {response}. It seems to be everything okay but...
When I switch my tab on a landscape or portrait mode the WebView is recreated, onNewPicture are started but the method public void init(String json) in the JsImpl is often not called at all!
So if i change orientation, sometimes js works, sometimes doesn't work. No exception, no errors...
Who faced with the same problem?
Below is full code
public class NextActivity extends Activity {
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
final WebView wv = (WebView) findViewById(R.id.WebView);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("file:///android_asset/index.html");
wv.addJavascriptInterface(new JsImpl(), "JsImpl");
wv.setPictureListener(new PictureListener() {
#Override
public void onNewPicture(WebView view, Picture picture) {
wv.loadUrl("javascript: JsImpl.init('{responce}');");
}
});
}
class JsImpl {
private final static String LOG_TAG = "JsImpl";
#JavascriptInterface
public void init(String json) {
Log.d(LOG_TAG, json);
}
}
}
html code is not needed here, just put on the assets dir an empty html file index.html.
EDIT:
I've found one soution but i dont know exactly is it correct varion. But it works.
I added handler loop
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (isJSSetup) return;
Log.i("handler-loop", "JS didn't handle. Reload page");
wv.loadUrl(CONTENT_PAGE);
handler.postDelayed(this, 1000);
}
}, 1000);
when #JavascriptInterface init(String json) is called, isJSSetup became true. In handler loop i check if JS is setup or no if (isJSSetup) return;. If no - i reload URL again wv.loadUrl(CONTENT_PAGE) and try to call init(String json). So long as it is not going to work. It's hardcode, so i'm still looking for a good solution.
I hope this will help, but I can't say for sure because you are not showing how your WebView is restored after orientation changes.
I was having very hard time making my nested fragments to work properly after orientation changes. I wanted to retain the form values and all functionality during screen rotations. It all worked fine except the JavascriptInterface was NEVER working after orientation changes.
My WebView is restored in the onCreateView. I had to remove the restoreState call for my WebView and it all works now.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.layoutT4, container, false);
webView = (WebView) rootView.findViewById(R.id.webViewT4);
prepareBrowser(); // the browser is initiated here including the JavascriptInterface
if (webView != null) {
String URL = (savedInstanceState == null) ? "" : savedInstanceState.getString("URL");
if (URL.equals("")) {
webView.loadUrl("yourhome.html");
} else {
//webView.restoreState(savedInstanceState.getBundle("webViewBundle")); // this line was preventing the JavascriptInterface to work properly
webView.loadUrl(URL); // this is saved in onSaveInstanceState - I just reopen the URL here, the PHP page will take care of reloading the data
}
}
return rootView;
}

Categories

Resources