I want to open a webpage in a WebView and click automatically on a button after the page has loaded. This is my current WebView class:
public class WebViewFragment extends Fragment {
...
#Override
public void onResume() {
super.onResume();
openUrl();
}
private void openUrl() {
setCookies();
if (urlToOpen != null) {
//tell webview to handle redirects (by default browser launches on redirects)
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (getActivity() != null)
((MainActivity) getActivity()).onShowLoading();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (getActivity() != null) {
executeJS();
((MainActivity) getActivity()).onHideLoading();
}
}
});
if (javascriptToExecute != null) {
webview.getSettings().setJavaScriptEnabled(true);
}
webview.loadUrl(urlToOpen);
}
}
private void executeJS() {
System.out.println("executeJS(): " + javascriptToExecute);
webview.loadUrl(javascriptToExecute);
}
}
I can use "javascript:$('#customer-info-edit').click();" or "javascript:document.getElementById('customer-info-edit').click();" both work fine.
But the problem is they work only one time. If I open the WebView for the first time, the button is clicked. However if I press physical back button and open the WebView again then the button is not clicked. Why isn't Javascript working every time?
I don't know what the problem exactly was, but I found a working solution: add 500ms delay before executing javascript.
Related
I am using WebView to view my offline webpage which contains few html pages named 1.html, 2.html and so on with main page index.html.It has only one Mainactivity and for now I'm using below code to exit the app when pressed twice. I want to add functionality to go back to previous page if pressed once and exit the app when pressed twice.
Here is the code for now which exit the app if pressed twice
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit",
Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
Any help would be much much appreciated.
boolean isDouble = false;
private int DURATION = 1000;
#Override
public void onBackPressed() {
if (isDouble) {
finishAndRemoveTask();
return;
}
isDouble = true;
finish();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
isDouble=false;
}
}, DURATION);
}
Im not so sure its a good pattern because it would be confusing to the user, if you want double back to exit the activity, and a single back to go to the previous page, you should consider adding a back button to activity title where users would have a dedicated back button. Notwithstanding though, what you can do in this case is go to the previous page once the timeout is expired as shown below
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
//super.onBackPressed(); use finish instead to close activity
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit",Toast.LENGTH_SHORT).show();
goBack();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
public void goBack(){
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
}
Hope it helps, Goodluck
I have an android activity that holds the webview and I have a page that contains a local variable marks. The local variable will be increased when user got the correct answer. In the webpage, there is a button called exit which is supposed to close the webpage and go back to the activity in android, and it should carry the local variable marks back to the activity too. I want to ask how the exit button can be done in the webpage to close the page and return local variable by using Javascript and how can the activity in android receive the local variable from the webpage.
My activity in android:
private WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
try {
webview.setWebViewClient(new WebViewClient());
webview.loadUrl("file:///android_asset/index.html");
}
catch(Exception ex)
{
ex.printStackTrace();
}
setContentView(webview);
}
My exit button is a div:
<div class="exit" onclick="finish()">Exit</div>
I am going to use the finish() function to return the variable and close the webpage back to the activity in android.
function finish() {}
To notify the host application that a page has finished loading. Then Call onPageFinished()
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
}
});
SOURCE
you can do one thing..On click on the exit call any url like http://../getmark?marks=2 and once url load in the webview finish/ exit from webview. In the activity
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// parse the url here to get marks
}
});
Register a javascriptinterface to your webview in onCreate:
this.webview.addJavascriptInterface(new MyJSInterface(this), "Android");
Implement setCount method in your Activity:
public void setCount (int count) {
//do what ever you want with count
}
Make a new JavascriptInterface-Class:
public class MyJSInterface {
private YourActivity yourActivity = null;
public MyJSInterface (YourActivity yourActivity) {
this.yourActivity = yourActivity;
}
#JavascriptInterface
public void invoke (int count) {
this.yourActivity.setCount(count);
}
}
And in javascript:
function finish(marks) {
if (Android !== undefined) {
if (Android.invoke !== undefined) {
Android.invoke(marks);
}
}
}
I have a problem with Javascript in WebView. Currently I have a ViewPager, which adds View dynamically when needed. Before add a view to viewpager, I inflate it and load an embedded webview inside:
LayoutInflater inflater = this.getLayoutInflater();
FrameLayout v = (FrameLayout) inflater.inflate(R.layout.notebook_page, null);
setupWebView(v);
pagerAdapter.addView(v);
pagerAdapter.notifyDataSetChanged();
In the webview, first I load a local html, and then inject a JS fuction to set several input on HTML.
private void setupWebView(View v) {
myWebView = (WebView) v.findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/web_resources/index.html");
myWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
super.onPageFinished(myWebView, url);
Log.d("WebView Content", "Injecting JS");
myWebView.loadUrl("javascript:function('" + input_var + "')");
}
});
}
Funtion setupWebView is called correctly for every view inflated, however, the JS function does not work properly
The same piece of code works perfectly in an Activity, if there is only 1 page. Just in ViewPager, where there are more than 1 pages to display the webviews, JS only loads in the last page.
Do you have any suggestion?
Firstly, on 5.0 Android you should use different method to use javascript. I use this snippet of code.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');", new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.e("LoginActivity onReceiveValue", s);
}
});
} else
webView.postUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');", null);
Also, you should include #JavascriptInterface tag on your javascript method.
#SuppressWarnings("unused")
#JavascriptInterface
public void processHTML(final String html) {
//method called from javascript
}
I have a website with href in it which redirected me to https
<a id="mA" href="javascript:pLogin(2)" class="login-link__link private-cab-link"><i class="icon-user"></i>Авторизация</a>
So, I can click on it by JavaScript. It works in chrome console
javascript:(function(){document.getElementById('mA').click();})()
Now I'm trying to do the same in WebView by clicking my app's button.
public class RostelecomLoginActivity extends Activity {
WebView webView;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_rostelecom_login);
Intent webIntent = getIntent();
String url = webIntent.getStringExtra("url");
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MeWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSaveFormData(true);
webView.getSettings().setSavePassword(true);
webView.loadUrl(url);
Button buttoner = (Button) findViewById(R.id.button1);
buttoner.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
webView.loadUrl("javascript:(function(){document.getElementById('mA').click();})()");
}
});
}
}
I'm using MyWebViewClient to allow all certificates
public class MeWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
}
The js injection doesn't work. If I click on href in WebView it works.
What can be wrong?
click() isn't implemented in android js interface, you have to use HTML DOM Event Object, like this:
webView.loadUrl("javascript:(function(){"+
"l=document.getElementById('mA');"+
"e=document.createEvent('HTMLEvents');"+
"e.initEvent('click',true,true);"+
"l.dispatchEvent(e);"+
"})()");
You'll have to add a javaScript interface to the WebView to call a JavaScript function from android code.
Try something like this:-
Button buttoner = (Button) findViewById(R.id.button1);
buttoner.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
JavascriptInterface javasriptInterface = new JavascriptInterface(RostelecomLoginActivity.this);
webView.addJavascriptInterface(javasriptInterface, "MyInterface");
webView.loadUrl("javascript:(function(){document.getElementById('mA').click();})()");
}
});
final Context myApp = this;
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
#SuppressWarnings("unused")
public void showHTML(String html)
{
new AlertDialog.Builder(myApp)
.setTitle("HTML")
.setMessage(html)
.setPositiveButton(android.R.string.ok, null)
.setCancelable(false)
.create()
.show();
}
}
final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:window.HTMLOUT.showHTML(''+document.getElementsByTagName('html')[0].innerHTML+'');");
}
});
/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");
In to the above code after
new AlertDialog.Builder(myApp)
.setTitle("HTML")
.setMessage(html)
.setPositiveButton(android.R.string.ok, null)
.setCancelable(false)
.create()
.show();
I want to set visibility of the button true and false but it gives me error does any one have any idea why its happens and have any solution?
Thanks in advance
Finally I got the solution of the error. I'm using:
btn.post(new Runnable() {
#Override
public void run() {
btn.requestFocus();
btn.setVisibility(0);
}
}
And after that I'm starting a new thread when I want to show the button