I have a WebView app that links to my shop url, the problem here is that there is a button (add to homescreen) button and I want to hide that button Class in my WebView.I have tried to hide it using javascript in OnProgressChange method and it works but, when i click the category button and press the home button or go back to home again, the "add to home screen button" appears again. Can someone please help me or guide me how to achieve this task. this is the shop link
//WebView Settings and Configuration
Wview = (WebView) findViewById(R.id.webView);
WebSettings webSettings = Wview.getSettings();
webSettings.setJavaScriptEnabled(true);
Wview.setWebChromeClient(new chromeClient());
Wview.setWebViewClient(new myClient());
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
Wview.loadUrl(homeUrl);
}
private class myClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return super.shouldInterceptRequest(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean a = true;
if (url !=null && url.startsWith("whatsapp")){
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));
return true;
}
else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
}
else if (url.startsWith("rate:")) {
final String app_package = getPackageName(); //requesting app package name from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + app_package)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + app_package)));
}
}
else if (url.startsWith("share:")) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, view.getTitle());
intent.putExtra(Intent.EXTRA_TEXT, view.getTitle()+"\nVisit: "+(Uri.parse(url).toString()).replace("share:",""));
startActivity(Intent.createChooser(intent, getString(R.string.share_w_friends)));
}
else if (url.startsWith("exit:")) {
exitApp();
}// opening external URLs in android default web browser
else if (ext_url && !hostname(url).equals(homeUrl)) {
Wview(url,true, wError_counter);
// else return false for no special action
} else {
a = false;
}
return a;
}
@Override
public void onPageFinished(WebView view, String url) {
if(!errorOccured){
findViewById(R.id.welcome).setVisibility(View.GONE);
findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
super.onPageFinished(view, url);
}
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
errorOccured=true;
findViewById(R.id.webView).setVisibility(View.GONE);
findViewById(R.id.welcome).setVisibility(View.VISIBLE);
//Intent intent = new Intent(getApplicationContext(), ErrorActivity.class);
// startActivity(intent);
}
}
//Random ID creation function to help get fresh cache every-time webview reloaded
public String random_id() {
return new BigInteger(130, random).toString(32);
}
//Opening URLs inside webview with request
void Wview(String url, Boolean tab, int error_counter) {
if(error_counter > 2){
wError_counter = 0;
exitApp();
}else {
if(tab){
if(cTAB) {
CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();
intentBuilder.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimary));
intentBuilder.setSecondaryToolbarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
intentBuilder.setStartAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right);
intentBuilder.setExitAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right);
CustomTabsIntent customTabsIntent = intentBuilder.build();
try {
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(url));
} catch (ActivityNotFoundException e) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
}else{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
} else {
if (url.contains("?")) { // check to see whether the url already has query parameters and handle appropriately.
url += "&";
} else {
url += "?";
}
url += "rid=" + random_id();
Wview.loadUrl(url);
}
}
}
//Getting host name
public static String hostname(String url){
if (url == null || url.length() == 0) {
return "";
}
int dslash = url.indexOf("//");
if (dslash == -1) {
dslash = 0;
} else {
dslash += 2;
}
int end = url.indexOf('/', dslash);
end = end >= 0 ? end : url.length();
int port = url.indexOf(':', dslash);
end = (port > 0 && port < end) ? port : end;
Log.w("URL Host: ",url.substring(dslash, end));
return url.substring(dslash, end);
}
private void exitApp() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
// Creating exit dialogue
public void ask_exit(){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(getString(R.string.exit_title));
builder.setMessage(getString(R.string.exit_subtitle));
builder.setCancelable(true);
// Action if user selects 'yes'
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
// Actions if user selects 'no'
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
// Create the alert dialog using alert dialog builder
AlertDialog dialog = builder.create();
// display the dialog when user press back button
dialog.show();
}
@Override
public void onBackPressed() {
if (Wview.canGoBack()) {
Wview.goBack();
} else if (ask_ExitDial) {
ask_exit();
} else {
super.onBackPressed();
this.finish();
}
}
private class chromeClient extends WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
Wview.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('sc-iQKALj cdqULD border border-gray-dae')[0].style.display='none'; " +
"})()");
super.onProgressChanged(view, newProgress);
}
}
private class touchlistener implements View.OnTouchListener {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
WebView.HitTestResult hitTestResult=((WebView)view).getHitTestResult();
hitResult=true;
return false;
}
}
}
So basically the problem is to detect changes inside WebView and react to them in a specific manner.
Changes inside WebView
can be of multiple types - actual reloads and Dom changes - are main ones we should listen to. While listening to the reloads is relatively easy and could be done either in WebViewClient.shouldInterceptRequest
or WebViewClient.shouldOverrideUrlLoading
callbacks, DOM changes are impossible to track via android WebView
API.
private class myClient extends WebViewClient {
...
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
Wview.evaluateJavascript("javascript:(function() { " +
"document.getElementsByClassName('sc-iQKALj cdqULD border border-gray-dae')[0].style.display='none'; " +
"})()");
return super.shouldInterceptRequest(view, url);
}
...
}
To track changes in DOM we can use JavaScript though and specifically MutationObserver
- you will have to inject your code with the implemented callback via WebView
js injecting capabilities. To do that, if your minimum API level is higher than 19, try using webView.evaluateJavascript
instead of webView.loadUrl
.
Also you may use Activity.onBackPressed
method and WebView.setOnKeyListener
conjunction. It will look something like this:
public void onBackPressed() {
if (Wview.canGoBack()) {
Wview.goBack();
Wview.evaluateJavascript("javascript:(function() { " +
"document.getElementsByClassName('sc-iQKALj cdqULD border border-gray-dae')[0].style.display='none'; " +
"})()");
} else if (ask_ExitDial) {
ask_exit();
} else {
super.onBackPressed();
this.finish();
}
}
Wview.setOnKeyListener((View.OnKeyListener) (v, keyCode, event) -> {
if (event.getAction() != KeyEvent.ACTION_DOWN)
return true;
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (Wview.canGoBack()) {
Wview.goBack();
Wview.evaluateJavascript("javascript:(function() { " +
"document.getElementsByClassName('sc-iQKALj cdqULD border border-gray-dae')[0].style.display='none'; " +
"})()");
} else {
((Activity) this).onBackPressed();
}
return true;
}
return false;
});
It may work or not depending on your web site architecture.
Thus your only option is to experiment and hope it will work. Generally work with webview on android is quite a pain so... yeah.
Hope it will help you somehow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With