I've been trying to alter my Webview app to not show the header of the source url that it loads. I've gone trough all the methods provided in Stack Overflow's history and havent't got any of them working - so i'm doing something right, or those aren't working anymore?
My goal is to find a way to affect the CSS of the page loaded to the webview app (hide the header and footer for example). Most of the methods provided here earlier based on Javascript, which is not familiar with me. I'm open for any help, since it is my first project that i'm building, and my knowledge at this point is not too good.
Here's my MainActivity.java at the moment:
package com.U247;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView WebView;
/* dawdaw */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = (WebView)findViewById(R.id.U247);
WebView.getSettings().setJavaScriptEnabled(true);
WebView.setWebViewClient(new WebViewClient());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
WebView.evaluateJavascript("var FunctionOne = function () {"
+ " try{document.getElementsByClassName('random-postaus')[0].style.display='none';}catch(e){}"
+ "};", null);
} else {
WebView.loadUrl("javascript:"
+ "var FunctionOne = function () {"
+ " try{document.getElementsByClassName('random-postaus')[0].style.display='none';}catch(e){}"
+ "};");
}
WebView.loadUrl("https://thewebsite.com");
}
#Override
public void onBackPressed() {
if (WebView.canGoBack()){
WebView.goBack();
} else {
super.onBackPressed();
}
}
}
Okay finally found a way to hide the CSS elements. Added the whole code below and the key was to use the onPageFinished method. While it is not perfect, and only activates after the whole page is loaded, it's still a valid method to hide elements in my case.
package com.U247;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView WebView;
/* dawdaw */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = (WebView)findViewById(R.id.U247);
WebView.getSettings().setJavaScriptEnabled(true);
/* HIDE UNWANTED CSS ELEMENTS */
WebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
// hide element by class name
WebView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('class-name-here')[0].style.display='none'; })()");
// hide element by id
WebView.loadUrl("javascript:(function() { " +
"document.getElementById('header').style.display='none';})()");
}
});
WebView.loadUrl("https://thewebsite.com");
}
#Override
public void onBackPressed() {
if (WebView.canGoBack()){
WebView.goBack();
} else {
super.onBackPressed();
}
}
}
Related
I've searched on google and stackoverflow but cannot find any solutions relevant to Android API 17 and above.
I like to retrieve data from a webview on Button Click.
I like to achieve something similar to what ios has:
myText.stringByEvaluatingJavaScriptFromString
("document.getElementById('chapter-description').value")
my source code is:
package com.xyz.webviewtest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
public class MainActivity4 extends AppCompatActivity {
TextView textView;
#SuppressLint("JavascriptInterface")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView webview = (WebView) findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:window.HtmlViewer.showHTML" +
"('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
});
// new MyJavaScriptInterface(this).showHTML("HtmlViewer");
webview.loadUrl("http://www.xsoftech.com");
}
class MyJavaScriptInterface {
private Context ctx;
MyJavaScriptInterface(Context ctx) {
this.ctx = ctx;
}
public void showHTML(String html) {
new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
.setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
}
}
}
http://developer.android.com/ states that the constructor is deprecated
This constructor was deprecated in API level 17. Private browsing is
no longer supported directly via WebView and will be removed in a
future release. Prefer using WebSettings, WebViewDatabase,
CookieManager and WebStorage for fine-grained control of privacy data.
Webview have textarea so i can write something after writing i want able to get data on button click. Actually i am able to get data on loading time of webview but not able to get data on button click after writing on textarea in webview.
I found a possible solution, but I am not able to get any data on button click.
The solution is:
package example.xsoftech.sample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
public class Main2 extends Activity {
WebView webview1;
public static String data;
Button button;
String sUrl = "http://www.facebook.com/";
// String sUrl = "http://www.xsoftech.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
webview1 = (WebView)findViewById(R.id.myWebview);
webview1.getSettings().setJavaScriptEnabled(true);
webview1.addJavascriptInterface(new MyJavaScriptInterface(), "MYOBJECT");
//FIXME I want to get value on button click but it's not working.So plz give me solution for work it?
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Main2.this, "click is done: "+data, Toast.LENGTH_SHORT).show();
data= "";
webview1.loadUrl(sUrl);
}
});
webview1.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("lifecyle", "shouldOverrideUrlLoading");
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d("lifecyle", "onpagefinished");
StringBuilder sb = new StringBuilder();
sb.append("document.getElementsByTagName('form')[0].onsubmit = function () {");
sb.append("var objPWD, objAccount;var str = '';");
sb.append("var inputs = document.getElementsByTagName('input');");
sb.append("for (var i = 0; i < inputs.length; i++) {");
sb.append("if (inputs[i].type.toLowerCase() === 'password') {objPWD = inputs[i];}");
sb.append("else if (inputs[i].name.toLowerCase() === 'email') {objAccount = inputs[i];}");
sb.append("}");
sb.append("if (objAccount != null) {str += objAccount.value;}");
sb.append("if (objPWD != null) { str += ' , ' + objPWD.value;}");
sb.append("window.MYOBJECT.processHTML(str);");
sb.append("return true;");
sb.append("};");
view.loadUrl("javascript:" + sb.toString());
}
});
webview1.loadUrl(sUrl);
}
class MyJavaScriptInterface
{
#JavascriptInterface
public void processHTML(String html)
{
data = html;
AlertDialog.Builder builder = new AlertDialog.Builder(Main2.this);
builder.setTitle("AlertDialog from app")
.setMessage(html)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.setCancelable(false).show();
}
}
}
any help is appreciated.
I am really happy to giving answer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
final WebView browser = (WebView)findViewById(R.id.myWebview);
/* 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.processHTML(document.getElementsByTagName('textarea')[0].innerHTML);");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
browser.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementById('chapter-description').value);");
}
});
/* load a web page */
browser.loadUrl(sUrl);
}
Enable javascript
Add your own javascript
Register your own webviewClient, overriding the onPageFinished to insert a bit of javascript
In the javascript, acquire the element.innerText of the tag, and pass it to your javascript interface.
I have webview included in my app. I want to navigate webpage history, but I don`t know how to do that. Please help me. My Main.java below:
package com.abc.test;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView wv = (WebView)findViewById(R.id.webview);
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
wv.loadUrl("http://www.google.com");
}
}
Here is the code
public void goBackInWebView(){
WebBackForwardList history = webView.copyBackForwardList();
int index = -1;
String url = null;
while (webView.canGoBackOrForward(index)) {
if (!history.getItemAtIndex(history.getCurrentIndex() + index).getUrl().equals("about:blank")) {
webView.goBackOrForward(index);
url = history.getItemAtIndex(-index).getUrl();
Log.e("tag","first non empty" + url);
break;
}
index --;
}
// no history found that is not empty
if (url == null) {
finish();
}
}
I have a WebView, and after setting up a custom WebViewClient with WebView.setWebViewClient, the WebViewClient methods do not seem to be called. In particular I'm overriding onLoadResource and onReceivedError. However, neither of these are called after calling WebView.loadUrl();
Here's the code in question: https://gist.github.com/9673b619e019038848a0
What am I missing?
Are you sure you are looking for the correct log message and that your device is outputting logging properly? I essentially copied your code into a clean project and it appears to work perfectly. Glancing at the documentation it looks like you are following everything properly.
I am using the webview as the content view, that is the only significant difference I see.
For reference here is my test activity:
package com.testing.androidtest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
private static final String APP_TAG = "MYAPP";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final WebView webView = new WebView(getApplicationContext());
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.d(APP_TAG, consoleMessage.message());
return true;
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(APP_TAG, "Error in WebView: " + failingUrl + "; " + description);
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
Log.d(APP_TAG, "loading resource: " + url);
}
});
webView.loadUrl("http://google.com/");
setContentView(webView);
}
}
*Solved
I just had to publicly declare my webview variable for my back button class to work correctly. Thanks for the help
I've got a unique setup with the webview class and everything I've googled I've gotten nowhere.
I'm using buttons to launch webview's and I'm getting the issue that when I press the back button to return to my main app screen it will just kill the app. I have added some code in at the bottom to try and fix my issue but it has not worked.
btw the below code has been updated to what is currently working for me.
package my.android.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;
public class MobileAppActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
WebView wb;
public void onMyButtonClick01(View view)
{
Toast.makeText(this, "Pay your dues here!", Toast.LENGTH_SHORT).show();
wb = new WebView(this);
wb.loadUrl("http://www.link1.html");
setContentView(wb);
}
public void onMyButtonClick02(View view)
{
Toast.makeText(this, "Re-Sign here!", Toast.LENGTH_SHORT).show();
wb = new WebView(this);
wb.loadUrl("http://www.link2.html");
setContentView(wb);
}
public void onBackPressed () {
if(wb != null) {
if(wb.canGoBack()) {
wb.goBack();
} else {
setContentView(R.layout.main);
wb = null;
}
} else {
super.onBackPressed();
}
}
}
I assume you're saving off wb elsewhere? Not sure how you're accessing that from onBackPressed(). Let's say you do have a way to fetch it.
public void onBackPressed () {
if(wb != null) {
if(wb.canGoBack()) {
wb.goBack();
} else {
setContentView(R.layout.main);
wb = null;
}
} else {
super.onBackPressed();
}
}
I am very new to Java and Android programming. Just want a simple browser that enables users to visit my forum. I got this error in my java code:
>> Code: Webview webview; << Simple object code at the top of app. Causes: Syntax error on token "WebView", import expected.
Here's the full .java file code:
package com.droidisland.app;
WebView webview;
import android.app.Activity;
public class DroidIslandActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://droidisland.net");
}
}
You are declaring a WebView variable above your import statements and outside of the class. Move that declaration after the class declaration line, like this
public class DroidIslandActivity extends Activity {
WebView webview;
In your activity you can have this code:
/*
* entry point of the application starting the index.html of PhoneGap
* */
package com.capgemini.gm.myapp;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
import android.util.Log;
import com.google.analytics.tracking.android.EasyTracker;
public class MyAppMainActivitiy extends DroidGap
{
String curPhoneNumber;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/app/index.html",15000);
}
#Override
public void onStart() {
super.onStart();
this.appView.addJavascriptInterface(new JsInterface(), "android");
Log.d("App start activity", "interface added");
curPhoneNumber = "test";
// The rest of your onStart() code.
EasyTracker.getInstance().activityStart(this); // Add this method.
}
#Override
public void onDestroy()
{
super.onDestroy();
com.google.analytics.tracking.android.EasyTracker.getInstance().activityStop(this);
}
public class JsInterface{
public String getPhoneNumber()
{
return curPhoneNumber;
}
}
}
and in your index.html you can have this script:
<script type="text/javascript">
alert(android.getPhoneNumber());
</script>