Search & Highlight a word from html webpage shown in webview? - javascript

I want to search and highlight a word in android webview, I tried with this code but it is not working. My code is here:
webview.findAll("a");
webview.setSelected(true);
webview.findNext(true);
try {
for (Method m : WebView.class.getDeclaredMethods()) {
if (m.getName().equals("setFindIsUp")) {
// m.setAccessible(true);
m.invoke(webview, true);
break;
}
}
} catch (Exception ignored)
{
Log.i("highlight error", ignored.toString());
}
This code is not setting any highlight on the selected word or not giving any error so please tell me how to search for and select a word in a webview ,currently i am trying for android version 3.2?

Setup a search button on your WebView layout.
Set up the WebView, and then a Search Button as follows. The popup dialog has a Cancel Button, a Search Button and an Edit Text for the search term. When search is pressed, each match of the EditText string will be highlighted in the WebView.
final Activity activity = this;
webView = (WebView) findViewById(R.id.yourWebView);
webView.setScrollbarFadingEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.clearCache(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.setTitle("Loading Web Page");
progressDialog.setIcon(R.drawable.ic_menu_allfriends);
progressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
webView.destroy();
finish();
} });
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if(progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
webView.loadUrl(yourStringURL);
Button search = (Button) findViewById(R.id.butSearch);
search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//set up button for search keyword of the webView
final Dialog dSearch = new Dialog(myActivity.this);
dSearch.setContentView(R.layout.search_keyword);
dSearch.setCancelable(true);
dSearch.setTitle(getString(R.string.yourTitle));
Button cancel = (Button) dSearch.findViewById(R.id.searchCancel);
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dSearch.dismiss();
}
});
Button search = (Button) dSearch.findViewById(R.id.searchAdd);
search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText etkw = (EditText) dSearch.findViewById(R.id.searchword);
String keyword = etkw.getText().toString();
dSearch.dismiss();
webView.findAll(keyword);
try
{
Method m = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
m.invoke(webView, true);
}
catch (Throwable ignored){}
}
});
dSearch.show();
}
});

Related

Android studio click on coords x y

Hi i want when i clicked on button automatically button2 is click with MotionEvent me = MotionEvent.obtain(SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_DOWN,
500,
935,
0);
button=(Button)findViewById(R.id.boutton);
button2=(Button)findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MotionEvent me = MotionEvent.obtain(SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_DOWN,
500,
935,
0);
view.dispatchTouchEvent(me);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Clicled",Toast.LENGTH_LONG).show();
}
});
};
You will need to use performClick() method to achieve this by using it inside the onClickListener of button
View.performClick();
Please check the following answers for more understanding:
How to simulate a button click using code?
Simulate Android button click programmatically
Also check the following documentation:
(https://developer.android.com/reference/android/view/View.html#performClick())

Intercept back Button to Go back in webView if pressed once and exit if pressed twice

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

Javascript not always working in WebView

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.

Two onClick actions one button at same time

I am developing a program in android studio. I want when I click a button then action will perform at the same time.
Function:
1st - Start count clicks
2nd - after 5 seconds that button disable
setDelay = new Handler();
btn = (Button) findViewById(R.id.bt);
final Button disableMe = (Button) findViewById(R.id.bt);
final TextView text = (TextView) findViewById(R.id.timeUp);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
startDelay = new Runnable(){
#Override
public void run(){
text.setText("Time Up!");
disableMe.setEnabled(false);
}
};
setDelay.postDelayed(startDelay, 5000);
}
});
txv = (TextView) findViewById(R.id.tx);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCounter ++;
txv.setText(Integer.toString(mCounter));
}
});
This can help
private int clicks = 0;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
final Button b = (Button)v;
if (clicks == 0){
// Means its the first time that a user click the button
// Start a thread that is going to disable the button after 5 seconds from first click
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run() {
b.setText("Time up");
b.setEnabled(false);
// Showing user clicks after button is disabled
showClicks();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
// Here we are just counting . . . . including the first click
countClicks();
}
});
Count clicks method
private void countClicks(){
++clicks;
// You can update your text view here
}
Showing total clicks
private void showClicks(){
Toast.makeText(this, Integer.toString(clicks), Toast.LENGTH_SHORT).show();
}
Just use a boolean variable to tell if the disable Runnable is started:
button.setOnClickListener(new View.OnClickListener() {
boolean disableRunnableStarted = false;
Runnable disableRunnable = new Runnable(){
#Override
public void run(){
//Running on UI thread to update button
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
button.setEnabled(false);
}
});
}
};
#Override
public void onClick(View v) {
if(!disableRunnableStarted) {
Log.d(TAG,"Starting disable runnable and incrementing counter...");
new Handler().postDelayed(disableRunnable,5000);
disableRunnableStarted = true;
//Here increment your counter
} else {
Log.d(TAG,"Just incrementing counter...");
//Here increment your counter
}
}
});
Replace MainActivity with your Activity's name, if executing in a Fragment replace by getActivity().
create new list like this :
ArrayList <View.OnClickListener> clickList = new ArrayList<>();
then add all your Listener :
final Runnable startDelay;
clickList.add(new View.OnClickListener(){
#Override
public void onClick(View v){
if (startDelay != null)
return;
startDelay = new Runnable(){
#Override
public void run(){
text.setText("Time Up!");
disableMe.setEnabled(false);
}
};
setDelay.postDelayed(startDelay, 5000);
}
});
clickList.add(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCounter ++;
txv.setText(Integer.toString(mCounter));
}
});
then , in your button add this Listener:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (View.OnClickListener c : clickList)
c.onClick(view);
}
});

programmatic click in Android WebView

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

Categories

Resources