android webview = webpage not found = where to add onReceivedError - javascript

I m a newbie, please guide me where to add the onReceivedError code.
This is my original code:
My static page directs to my website, if the internet is slow or no network connect, I get a error showing url, I would like to show another html error page, if possible even reload button.
Thanks in advance for guidance.
public class WebActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webcontent);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient()); //the lines of code added
webView.setWebChromeClient(new WebChromeClient()); //same as above
webView.loadUrl("file:///android_asset/index.html");
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
Where to place the below code: please guide
Or any improvements
#Override
public void onReceivedError(WebView WebResourceRequest WebResourceError) {
webView.loadUrl("file:///android_asset/errorpage.html");

It is set in new WebViewClient():
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/errorpage.html");
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
Now when an error is received, the web view will load that error page.

Related

Android webView - javascript code is not getting called

I try to load this javascript in my webview:
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
website = "https://www.blizz-z.de";
myWebView = findViewById(R.id.blizzView);
WebSettings settings = blizzView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
// Notify the host application that a page has finished loading.
public void onPageFinished(WebView view, String url)
{
myWebView.loadUrl(
"javascript:(function() {" +
"setInterval(function() {" +
+ "jQuery('#myInput').css('background', '#'+(Math.random()*0xFFFFFF<<0).toString(16));"
+ "}, 1000);"
+ "});"
);
}
}
...
}
But it is not getting executed. If I execute the script in my desktop browser, then it works. It changes the background color of my search bar on my website just for test purposes.
Is setInterval not supported in webView?
Update:
I tried it with the function js from #mohkamfer's answer:
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
website = "https://www.blizz-z.de";
blizzView = findViewById(R.id.blizzView);
WebSettings settings = blizzView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
// Notify the host application that a page has finished loading.
public void onPageFinished(WebView view, String url)
{
js(myWebView, "(function() {" +
"setInterval(function() {" +
+ "jQuery('#myInput').css('background', '#'+(Math.random()*0xFFFFFF<<0).toString(16));"
+ "}, 1000);"
+ "});"
);
}
}
...
}
public void js(WebView view, String code)
{
String javascriptCode = "javascript:" + code;
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(javascriptCode, new ValueCallback<String>() {
#Override
public void onReceiveValue(String response) {
Log.i("debug_log", response);
}
});
} else {
view.loadUrl(javascriptCode);
}
}
But it makes no difference.
Are you deploying on API 19 or higher? If so you'll have to use WebView#evalulateJavascript instead of WebView#loadUrl
I always use this method to simplify and quicken things a bit
public void js(String code) {
if (Build.VERSION.SDK_INT >= 19) {
this.evaluateJavascript(code, new ValueCallback<String>() {
#Override
public void onReceiveValue(String response) {
}
});
} else {
this.loadUrl("javascript:" + code);
}
}
I figured it out... I just had to call the code with jQuery(document).ready(function() {. The code was executed but did not changed anything because it was executed before the DOM was ready...
Solution:
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
website = "https://www.blizz-z.de";
myWebView = findViewById(R.id.blizzView);
WebSettings settings = blizzView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
// Notify the host application that a page has finished loading.
public void onPageFinished(WebView view, String url)
{
js(myWebView, "jQuery(document).ready(function() {" +
"setInterval(function() {" +
+ "jQuery('#myInput').css('background', '#'+(Math.random()*0xFFFFFF<<0).toString(16));"
+ "}, 1000);"
+ "});"
);
}
}
...
}
public void js(WebView view, String code)
{
String javascriptCode = "javascript:" + code;
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(javascriptCode, new ValueCallback<String>() {
#Override
public void onReceiveValue(String response) {
Log.i("debug_log", response);
}
});
} else {
view.loadUrl(javascriptCode);
}
}
Credits to #mohkamfer for contributing the js function.

Android Javascript function only works on initial load

In my Android Application, I have a WebView, before it displays anything from it though, I made it so that certain elements on my site do not display with javascript.It however only works on the first load, if you actually navigate through the site(click on a post for example) it will display all of the elements I don't want it to. It was working perfectly fine before, and now I cannot figure out why it isn't working. I'd appreciate any help!
mWebView = (WebView) view.findViewById(R.id.webView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
bar.setVisibility(View.VISIBLE);
mWebView.setVisibility(View.INVISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
mWebView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('fa fa-youtube')[0].style.display='none'; " +
"document.getElementsByClassName('fa fa-twitter')[0].style.display='none'; " +
"document.getElementsByClassName('menu-primary-container')[0].style.display='none'; " +
"document.getElementsByClassName('menu-toggle')[0].style.display='none'; " +
"document.getElementsByClassName('widget_slider_area')[0].style.display='none'; " +
"})()");
bar.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
super.onPageFinished(view, url);
}
});
mWebView.loadUrl("http://mywebsite.com");

"Uncaught TypeError: window.HTMLOUT.showHTML is not a function"

I am trying to inject JavaScript for reading on specific value while loading webView.
These are the properties i used for my webView.
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setCacheMode(2);
webView.getSettings().setDomStorageEnabled(true);
webView.clearHistory();
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setUseWideViewPort(false);
webView.getSettings().setLoadWithOverviewMode(false);
webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
and i am injecting javacript in my onPageFInished() method.
#Override
public void onPageFinished(final WebView view, final String url) {
webView.post(new Runnable() {
#Override
public void run() {
webView.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('input')[0].value+'</head>');");
}
});
super.onPageFinished(view, url);
}
Below code is MyJavaScriptInterface.
public class MyJavaScriptInterface{
#JavascriptInterface
public void showHTML(String html_data) {
if(html_data.contains("response_code")){
Log.e(TAG, " ======> HTML Data : "+ html_data);
new MakeQueryPayment().execute();
}
}
}
Error i captured from the Logcat.
01-08 17:56:43.701 I/chromium(27026): [INFO:CONSOLE(1)] "Uncaught TypeError: window.HTMLOUT.showHTML is not a function", source: (1)
I m facing this problem only in Samsung Galaxy Tab A, Model Number is SM-T550 , Android Version is 5.0.2. In other devices which we have it's working fine. Can any one please help me out from this.
Thanks in advance.
I try on Galaxy Tab 4, this code running well on this device.
WebView properties
WebView webView = new WebView(this);
setContentView(webView);
webView.clearHistory();
webView.clearCache(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setCacheMode(2);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setUseWideViewPort(false);
webView.getSettings().setLoadWithOverviewMode(false);
webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webView.loadUrl("http://stackoverflow.com/questions/34746626/uncaught-typeerror-window-htmlout-showhtml-is-not-a-function");
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
}
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
});
JavaScript Interface
public class MyJavaScriptInterface{
#JavascriptInterface
public void showHTML(String html_data) {
Log.e("", " ======> HTML Data : "+ html_data);
}
}
For me, as it was working fine before upgrading to the latest targetSDK, I just had to add the annotation #JavascriptInterface on all my functions.
Example:
#JavascriptInterface
public void eventDragStart() {
// do somthing
}

Android: Android 4.4.4 WebView upload image, but JavaScript check file type error

I use Android WebView to show a web server's web page in Android 4.4.4.
But at the server side, JavaScript check for the image file type fails. So I cannot upload my image.
But without changing the server side code, I can upload image successfully in iOS WebView and on desktop using the same image file.
The following is my Server side JavaScript image checker code
var check_file = function (file) {
if (file.size > 1048576 * 10) {
upload_err_hdlr(413);
return false;
}
alert("Before Check");
if (!file.type.match(/image\/(jpeg|png|gif|jpg)/)) {
alert("Check fail");
upload_err_hdlr(415);
return false;
}
alert("Check successfully");
return true;
};
after I upload the image via Android 4.4.4 WebView, it shows an alert dialog
1. Before Check
2. Check fail
The following is my Android code
public class MainActivity extends Activity {
private static final int FILE_CHOOSER_RESULT_CODE = 1;
WebView mWebView;
private ValueCallback<Uri> mUploadMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new CustomWebViewClient());
mWebView.setWebChromeClient(new WebChromeClient() {
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
}
});
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
CookieManager.setAcceptFileSchemeCookies(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
mWebView.loadUrl("http://192.168.1.30:5000/dashboard");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == FILE_CHOOSER_RESULT_CODE) {
if(mUploadMessage == null)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
Log.d("Ting", "after result:" + result);
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
private class CustomWebViewClient extends WebViewClient {
}
}
The Android log "Ting" shows:
02-02 11:44:14.782 12456 12456 D Ting : after result:content://media/external/images/media/12255
The Uri is content://media/external/images/media/12255
This is the uploaded fail image
Anyone has any idea?
Thanks in advance.
Eric
======================
Additional Information:
I print the file content in JavaScript.
alert(JSON.stringify(file));
And the shows
{"webkitRelativePath":"","lastModified Date":"2015-01-17T10:04:30.000Z","name":"12255","type":"","size":2369496}
It seems that the uploaded image file has no "type" attribute.
Anyone knows why?
Thanks.
it's because file type isn't supported in Mobile browsers ,
check File type Support
You can try to check the file type using Regular expression :
if((/\.(gif|jpg|jpeg|tiff|png)$/i).test("filename")) {
// the file is an image
} else {
//file type is different than (JPEG,PNG,GIF,TIFF)
}

calling a javascript function from android

I'm trying to call a javascript function from java android code. i tried to look at all previous questions concerning this but nothing seems to be working. are there any suggestions? thanks!
javascript code:
<html>
<head>
<script language="javascript">
function doSomething() {
alert('hey!!!!!!!');
}
</script>
</head>
<body>
ilana
</body>
</html>
java code (from an activity on create)
final WebView webview=(WebView)findViewById(R.id.myWebView);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new JavaScriptInterface(this), "Android");
webview.loadUrl("file:///android_asset/www/index.html");
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("javascript:doSomething()");
my updated (but still not working) code is:
javascript:
<html>
<head>
<script type="text/javascript">
function doSomething(){
alert("hello");
}
</script>
</head>
<body>
hello hello hello!
</body>
</html>
java:
final WebView webview=(WebView)findViewById(R.id.myWebView);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/www/index.html");
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:doSomething()");
}
});
I think you have to wait the end of loading page
try that
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:doSomething()");
}
});
where is Main.this change for your activity this
webview.setWebChromeClient(new WebChromeClient(){
#Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result){
new AlertDialog.Builder(Main.this)
.setTitle("Alert")
.setMessage(message)
.setPositiveButton("OK",
new AlertDialog.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
});
# comments #
my onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = (WebView)findViewById(R.id.webView1);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d("", "!!!! here 1 !!!!");
view.loadUrl("javascript:doSomething()");
}
});
webview.setWebChromeClient(new WebChromeClient(){
#Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result){
Log.d("", "!!!! here 2 !!!!");
new AlertDialog.Builder(Main.this)
.setTitle("Alert")
.setMessage(message)
.setPositiveButton("OK",
new AlertDialog.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
});
webview.loadUrl("file:///android_asset/index.html");
You have used language="javascript", the correct attribute is type="text/javascript"

Categories