Visit Last Loaded URL - webview

I'm making an app in Xamarin android where user navigates. The app contains webview. When a user opens webview, url gets loaded and browsing can be done. When he ends the app and opens it again, URL is loaded again instead of viewing last visited URL.
I don't know what I'm doing wrong here.
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.SetWebViewClient(new MyWebClient());
CookieManager.Instance.SetAcceptCookie(true);
webView.Settings.JavaScriptEnabled = true;
webView.Settings.SetAppCacheEnabled(true);
webView.LoadUrl(getUrl());
webView.SetPadding(0, 0, 0, 0);
webView.Settings.SetSupportZoom(true);
}
public void saveUrl(String url)
{
ISharedPreferences sp = GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
ISharedPreferencesEditor editor = sp.Edit();
editor.PutString("SAVED_URL", url);
editor.Commit();
}
public String getUrl()
{
ISharedPreferences sp = GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
//If you haven't saved the url before, the default value will be google's page
return sp.GetString("SAVED_URL", "http://google.com");
}
public void onPageFinished(WebView view, String url)
{
this.onPageFinished(view, url);
saveUrl(url);
}
}
internal class MyWebClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return false;
}
}

You have placed onPageFinished method in an Activity. It should be overridden in MyWebClient class as below:
internal class MyWebClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return false;
}
public override void OnPageFinished(WebView view, String url)
{
base.OnPageFinished(view, url);
//Save the url here.
//This method itself gives you the last url loaded as it's url Parameter.
ISharedPreferences sp = Application.Context.GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
ISharedPreferencesEditor editor = sp.Edit();
editor.PutString("SAVED_URL", url);
editor.Commit().
}
}
This method will be automatically called when URL finished loading and then you will store your loaded URL in this method.

Related

open inside and outside of webview

can you please tell me whats wrong here? i want open my website and facebook (Facebook logging plugin) in webview only. all other external link will open in other external browsers. below code allow facebook to open in external browser.
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (!url.contains ("https://kroybook.com/')'https://facebook.com/")
{
Uri uri = Uri.parse(url);
startActivity(Intent.createChooser(new Intent(Intent.ACTION_VIEW, uri), "Choose browser"));
CookieManager.getInstance().setAcceptCookie(true);
} else {
myWebView.loadUrl(url);
return true;
}
return false;
}
This the code i used
public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null && url.startsWith("whatsapp://")) { view.getContext().startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } else { return false; } }

Xamarin.Android webview does not open the file, but file upload works fine (need C# code)

I have WebView which works fine for file upload but when I click on files to open or download, nothing happens. but in normal browser when I click on file it is opened successfully. the intention of code is to open the file when it is clicked. file choose chrome extension is fine. I think there is need to add some code in WebViewListner block.
The activity code is here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Net;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace smartbookapp
{
[Activity(Label = "JobActivity")]
public class JobActivity : Activity
{
public WebView webview;
public IValueCallback mUploadMessage;
public static ProgressBar progressBar;
public static int FILECHOOSER_RESULTCODE = 1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Jobs);
webview = FindViewById<WebView>(Resource.Id.JobView);
// show progress bar
progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
//
webview.Settings.JavaScriptEnabled = true;
webview.Settings.SetAppCacheEnabled(true);
webview.Settings.AllowFileAccess = true;
webview.Settings.BuiltInZoomControls = true;
webview.SetWebViewClient(new WebViewListener());
webview.SetWebChromeClient(new JobWebChromeClient(this));
webview.LoadUrl("https://smartbook.pk/Jobs/index");
//
}
//
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Android.Net.Uri[] result = data == null || resultCode != Result.Ok ? null : new Android.Net.Uri[] { data.Data };
try
{
mUploadMessage.OnReceiveValue(result);
}
#pragma warning disable CS0168 // Variable is declared but never used
catch (Exception e)
#pragma warning restore CS0168 // Variable is declared but never used
{
}
mUploadMessage = null;
}
base.OnActivityResult(requestCode, resultCode, data);
}
// webview listener code here
public class WebViewListener : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
{
view.LoadUrl(request.Url.ToString());
return true;
}
public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
{
progressBar.Progress = view.Progress;
}
public override void OnLoadResource(WebView view, string url)
{
progressBar.Progress = view.Progress;
}
public override void OnPageFinished(WebView view, string url)
{
progressBar.Progress = 0;
}
}
public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back && webview.CanGoBack())
{
webview.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
}
// download files from webview
public class JobWebChromeClient : WebChromeClient
{
JobActivity WebViewActivity;
public JobWebChromeClient(JobActivity activity)
{
WebViewActivity = activity;
}
public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
{
WebViewActivity.mUploadMessage = filePathCallback;
Intent i = new Intent(Intent.ActionGetContent);
i.AddCategory(Intent.CategoryOpenable);
i.SetType("*/*");
WebViewActivity.StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), JobActivity.FILECHOOSER_RESULTCODE);
return true;
}
}
}
First of all, make sure your WebView has enabled javascript and the WebViewClient is set correctly.
WebView mWebview = FindViewById<WebView>(Resource.Id.webView1);
mWebview.Download += MWebview_Download;
var client = new WebViewClient();
mWebview.Settings.JavaScriptEnabled = true;
mWebview.SetWebViewClient(client);
mWebview.LoadUrl("your url");
Then, we shouldd achieve WebView.Download event(use DownloadManager to download the file)
private void MWebview_Download(object sender, DownloadEventArgs e)
{
var url = e.Url;
DownloadManager.Request request = new
DownloadManager.Request(Uri.Parse(url));
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted); //Notify client once download is completed!
request.SetDestinationInExternalPublicDir(Environment.DirectoryDownloads, "CPPPrimer");
DownloadManager dm = (DownloadManager)GetSystemService("download");
dm.Enqueue(request);
Toast.MakeText(ApplicationContext, "Downloading File",ToastLength.Long//To notify the Client that the file is being downloaded
).Show();
}

Android Webview If No Internet Error Custom Page

**Hi WebView for my application when there is no internet application opens and the site address is displayed for him when there is no internet error.I want to open the HML page, but even though I tried to help thank you.
-----------------------------------------------------------------------------------------------------------**
example
java
package com.app.xxxx;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class WebviewInits {
WebView webView;
SwipeRefreshLayout swipeRefreshLayout;
ProgressBar progressBar;
Context context;
public WebviewInits(WebView webView, SwipeRefreshLayout swipeRefreshLayout, ProgressBar progressBar,Context context) {
this.webView = webView;
this.swipeRefreshLayout = swipeRefreshLayout;
this.progressBar = progressBar;
this.context=context;
}
public void initWeb(){
webView.getSettings().setJavaScriptEnabled( true );
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCachePath("caches");
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setSavePassword(true);
webView.getSettings().setSaveFormData(true);
offlineLoad();//TODO Delete if you don't want offline load
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
context.startActivity(intent);
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.loadUrl(webView.getUrl());
}
});
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (!swipeRefreshLayout.isRefreshing()){ //If you didn't refresh the page by using swiperefresh it will show progressbar.
progressBar.setVisibility(View.VISIBLE);
}
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("https://play.google.com/") || url.startsWith("http://play.google.com/")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
Activity host = (Activity) view.getContext();
host.startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
// Google Play app is not installed, you may want to open the app store link
Uri uri = Uri.parse(url);
view.loadUrl("https://play.google.com/store/apps/" + uri.getHost() + "?" + uri.getQuery());
return false;
}
}
return false;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.INVISIBLE); //It will hide progressbar because our page loaded.
if (swipeRefreshLayout.isRefreshing()){
swipeRefreshLayout.setRefreshing(false); //This will hide swiperefresh icon if we refreshed.
}
super.onPageFinished(view, url);
}
});webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
}
//TODO Offline Cache Load
public void offlineLoad(){
webView.getSettings().setAppCacheMaxSize( 5 * 1024 * 1024 ); // 5MB Size of storage that it will take
webView.getSettings().setAppCachePath( context.getApplicationContext().getCacheDir().getAbsolutePath() );
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT ); // load online by default
if ( !WebviewInits.isNetworkAvailable(context) ) { // loading offline
webView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
}
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
}
If you want to handle error in WebView,
You should override onReceivedError according to the following code,
private class MyWebViewClient extends WebViewClient {
.
.
.
// api<23
#Override
public void onReceivedError(WebView view, int errorCode, String description, String url) {
view.stopLoading();
webview.loadUrl("file:///android_asset/error/error.html"); // load error page from asset folder
// handle error
}
// api> 23
#Override
#TargetApi(android.os.Build.VERSION_CODES.M)
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
view.stopLoading();
webview.loadUrl("file:///android_asset/error/error.html"); // load error page from asset folder
// handle error
// super.onReceivedError(view, request, error);
}
.
.
.
}
also, you can check the connection in shouldOverrideUrlLoading, and if is not connected load error page, try this :
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!isNetworkAvailable(getApplicationContext())) {
showCustomErrorPage();
return true;
}
.
.
.
}
showCustomErrorPage function :
private void showCustomErrorPage() {
webview.loadUrl("file:///android_asset/error/error.html");
}

Xamarin/Android webview hide website element/class

I'm trying to make a little android app showing a webview loading a website.
I got it to show it with the following code snippets. But what I need now is to hide some elements on the header and the footer(a menu for example). I thought I could do it not loading some classes from the webpage, but I'm not sure how to properly do it. Do anyone have some experience on this to share some light? :)
Thanks in advance.
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
fab.Click += FabOnClick;
DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, Resource.String.navigation_drawer_open, Resource.String.navigation_drawer_close);
drawer.AddDrawerListener(toggle);
toggle.SyncState();
NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
navigationView.SetNavigationItemSelectedListener(this);
wbv = FindViewById<WebView>(Resource.Id.webView1);
wbv.SetWebViewClient(new ExtendWebViewClient());
WebSettings webSettings = wbv.Settings;
webSettings.JavaScriptEnabled = true;
wbv.LoadUrl(txtUrl);
}
internal class ExtendWebViewClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return true;
}
}
edit: Just to reflect the changes to the second class
public class ExtendWebViewClient : WebViewClient
{
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
string js = "var myElements = document.getElementsByClassName('fusion-main-menu');" +
" myElements[0].style.display = 'none'; ";
if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
{
view.EvaluateJavascript(js, null);
}
else
{
view.LoadUrl(js);
}
}
}
Since you have enabled javascript, there will be a function to run the script in the webview.
This is the code of WebView using Xamarin.Forms.WebView and this is how you can hide any element of webview using it's id.
var hide = await webview.EvaluateJavaScriptAsync("document.getElementById('UserName').style.display = 'none';");

open ads in external browser in webview android

I created app with webview, and i want load all internal links in webview and load external links in android browser. Now problem is I am using html ads and when i click on ads i want open external browser, but its opening in webview. only problem with ads otherwise everything is works fine. So how can i do this?
My code is below:
`class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().equals("www.mysite.com")) {
view.loadUrl(url);
return true;
}else{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;}}`
You code should be:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.mysite.com")) {
return true;
}else{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return false;
}
}
All I changed was:
1.) Returning true loads the URL in the webview, no need for view.loadUrl()
2.) Return false when you broadcast the ACTION_VIEW intent
I did the some modifications and it is working perfectly for banner ads.
I have made following changes:
changed if condition.
I am returning false for 'if' block as documentation says:
If WebViewClient is provided, return true means the host application
handles the url, while return false means the current WebView handles
the url
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (url.contains("www.mysite.com"))
{
view.loadUrl(url);
return false;
}else
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}

Resources