How to show local html file into webview? - javascript

I want show my local html file into webview .I use this codes :
WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wv=new WebView(this);
setContentView(wv);
try {
InputStream stream = this.getAssets().open("index.html");
int sreamsize = stream.available();
byte[] bufer = new byte[sreamsize];
stream.read(bufer);
stream.close();
String html= new String(bufer);
wv.loadData(html, "text/html", "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Now I can see elements into webview with out css and js effect . How to solve this?

Try this:-
WebView wv;
wv = (WebView) findViewById(R.id.webView1);
WebSettings webViewSettings = wv.getSettings();
webViewSettings.setJavaScriptEnabled(true);
webViewSettings.setDomStorageEnabled(true);
wv.loadUrl("file:///android_asset/index.html");

Try this:-
WebView wv;
wv = (WebView) findViewById(R.id.webView1);
wv.loadUrl("file:///android_asset/index.html");

Try to replace
try {
InputStream stream = this.getAssets().open("index.html");
int sreamsize = stream.available();
byte[] bufer = new byte[sreamsize];
stream.read(bufer);
stream.close();
String html= new String(bufer);
wv.loadData(html, "text/html", "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
with
wv.loadUrl("file:///android_asset/index.html");
And try again.
Update
For JS get works perfectly
try
WebSettings webViewSettings = wv.getSettings();
webViewSettings.setJavaScriptEnabled(true);
webViewSettings.setDomStorageEnabled(true);
As #Sabari preferred.

Have you tried just doing wv.loadUrl("file:///android_asset/index.html");?

Related

unable to load html into webview from html string

I'm trying to save a page html code into a string, then load it to a webview, I managed to get full HTML code successfully, however when I try to load it into webview, somehow it webview remove all content in
Here is how I initialized webView:
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
webView.getSettings().setGeolocationEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(new MyWebViewClient());
Webclient:
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
siteAddressBar.setText(url);
view.loadUrl(url);
Site = url;
return true;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onPageFinished(WebView view, String url) {
//view.loadUrl();
view.evaluateJavascript("(function() {return document.getElementsByTagName('html')[0].outerHTML;})();", new ValueCallback<String>() {
#Override
public void onReceiveValue(final String value) {
JsonReader reader = new JsonReader(new StringReader(value));
reader.setLenient(true);
try {
if (reader.peek() == JsonToken.STRING) {
String domStr = reader.nextString();
if (domStr != null) {
htmlCode = domStr;
Log.e("Stonmrigal1",domStr);
}
}
} catch (IOException e) {
// handle exception
} finally {
//IoUtil.close(reader);
}
}
});
}
}
and Then tried to load html like this:
webView.loadData(htmlCode, "text/html; charset=utf-8", "UTF-8");
I get response like this:
<html class="js backgroundsize borderimage csstransitions fontface svg details progressbar meter no-mathml cors xxsmallview wb-enable" dir="ltr" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body></body>
</html>
Solved, I used
webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

Get an image src from a webview in android

I am trying to get the src of a captcha image found in a webview but when i type the below code the output says:
Uncaught TypeError: Cannot read property 'src' of null
and another question if i get the image src how can i put the image in an image view?
any help will be really appreciated
here is my code so far:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.wv) ;
mImgCaptcha = (ImageView) findViewById(R.id.imgCaptcha);
done = (Button) findViewById(R.id.done);
contentView = (TextView) findViewById(R.id.textView);
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.password);
code = (EditText) findViewById(R.id.code);
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
wv.getSettings().setDomStorageEnabled(true);
wv.loadUrl("https://noor.moe.gov.sa/NOOR/Login.aspx");
wv.loadUrl("javascript:var a = document.getElementById('imgCaptcha').src;");
System.out.println(wv.getUrl());
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
wv.loadUrl("javascript:var x = document.getElementById('tbPublic').value = '" + username.getText().toString() + "';");
wv.loadUrl("javascript:var x = document.getElementById('tbPrivate').value = '" + password.getText().toString() + "';");
wv.loadUrl("javascript:var x = document.getElementById('tbCaptcha').value = '" + code.getText().toString() + "';");
try {
Thread.sleep(2000);
wv.loadUrl("javascript:(function(){" +
"l=document.getElementById('btnLogin');" +
"e=document.createEvent('HTMLEvents');" +
"e.initEvent('click',true,true);" +
" l.dispatchEvent(e);" +
"})()");
} catch (InterruptedException e) {
e.printStackTrace();
}
It's because the page is not loaded yet when you are trying to query the DOM. You need to query the DOM when you can be sure that the page has loaded.
We need to set the WebViewClient for the webview and then listen to onPageFinished event. The code might look something like this:
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// you can now query the DOM.
webView.loadUrl("javascript:var a = document.getElementById('imgCaptcha').src;");
}
});
Further reading: https://developer.android.com/reference/android/webkit/WebViewClient#onPageFinished(android.webkit.WebView,%2520java.lang.String)

Injecting CSS into WebView not working onPageFinished

Here's my code for injecting CSS into a Webview:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Ubqari");
ww = (WebView) findViewById(R.id.ww);
ww.getSettings().setJavaScriptEnabled(true);
ww.getSettings().setDomStorageEnabled(true);
ww.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
injectCSS();
}
});
ww.loadUrl("http://ubqari.org");``
}
And here's injectCSS function:
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
ww.loadUrl("javascript:(function() {" +
"alert('Hello! I am an alert box!');"+
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
I don't know what's going wrong in this code. My style.css code is correct but the problem is in the onPageFinished section. It's not injecting the CSS when the page has finished loading. Any expert can answer me?

Android WebView Auto Sign In

Following is the code which is I am implementing:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView) findViewById(R.id.webTask);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSaveFormData(false);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
else webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.loadUrl("javascript:document.getElementById('user_id').value='" + new String ("xxx")+ "';javascript:document.getElementById('password').value = '" + new String("xxx") + "';");
}
});
webView.loadUrl(URL);
But nothing happens infact web view turns blank and shows text written on its left corner "xxx"
Please help. already searched 3 to 4 hours and of no avail
At last i have solved the problem. the javascript was not being run because my targeted sdk was >= KITKAT.
So, in order to avoid the problem you have to use webView.evaluateJavascript(yourScript,null); for devices running on API level 19 or above.
Sample Code
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
webView.evaluateJavascript(yourScript,null);
}
else
{
webView.loadUrl(yourScript);
}

How to get the webview's vertical scroll postion while scrolling

I'm making some sort of book reader in webView. I have used the JavaScript, which dynamically creates the <img> tags via for loop. Look at the code's for loop, and every img tag is loaded with a different image from the URL.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
progressDialog = ProgressDialog.show(MainActivity.this,
"Loading Book...!", "Please Wait");
String htnlString = "<!DOCTYPE html><html><body style = \"text-align:center\"><script>var out = '';for (var counter = 1; counter <= 100; counter++){ out += '<img src=\"http://shiaislamicbooks.com/books_snaps/UR335/'+counter+'.jpg\"alt=\"Page No:'+counter+'\" width=\"100%\" />';}document.write(out);</script></body></html>";
wv.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Completed",
Toast.LENGTH_SHORT).show();
super.onPageFinished(view, url);
}
});
wv.loadDataWithBaseURL(null, htnlString, "text/html", "UTF-8", null);
}
Look at the htnlString:
Now I want to display a book pages information in a textView. This means, while scrolling the webview the textView should update the txtPage.
the scrollTo(x,y) is some how useful but I want the scroll listener for the webview.
WebView webview;
yPos = webview.getScrollY();
xPos=webview.getScrollX();

Categories

Resources