What is the best way to refresh webview in xamarin.forms - webview

I Handled webview success loading as the following :
void WebOnEndNavigating(object sender, WebNavigatedEventArgs e)
{
if (e.Result!=WebNavigationResult.Success)
{
//show message ... click on the button to retry
}
}
Here is event Refresh button :
void Refresh_Click(object Sender,EventArgs e)
{
webview.Source = (webview.Source as UrlWebViewSource).Url;
}
When I connect to the internet an click on the refresh button, Reloading webview success but on WebOnEndNavigating eventHandler WebNavigationResult is failed
what is the correct way to reload webview on Xamarin.Forms

Related

How to display awarded ad in method OnAppearing() using Xamarin

I want to display awarded ad when app is starting.
I load ads under InitializeComponent(); with this code:
public MainPage()
{
InitializeComponent();
//Load Interestitial Ad
CrossMTAdmob.Current.LoadInterstitial("ca-app-pub-9688730828394396/1781454910");
//Load Rewarded Ad
CrossMTAdmob.Current.LoadRewardedVideo("ca-app-pub-9688730828394396/9667490273");
}
I have two buttons when users click on them different ads starting with this code:
private void ShowReward_OnClicked(object sender, EventArgs e)
{
CrossMTAdmob.Current.ShowRewardedVideo();
}
private void ShowInterstitial_OnClicked(object sender, EventArgs e)
{
CrossMTAdmob.Current.ShowInterstitial();
}
I try to put CrossMTAdmob.Current.ShowInterstitial(); from one button in my OnAppearing() method but when I start application, the ad does not appear with this code:
protected override void OnAppearing()
{
base.OnAppearing();
SetEvents();
CrossMTAdmob.Current.ShowInterstitial();
}
Can I get some example how to display my ad when app is starting ?
I'm the author of the plugin you are using.
You should check if the ads is actually loaded before trying to show it.
You can use
IsInterstitialLoaded()
And
IsRewardedVideoLoaded().
If these methods return true, then you can show the ads.
If the result is always false then you have to understand why they are not loaded, you can see in the output windows if you receive some error messages.
Most of the time the reason is a wrong Id.

How to stop video playing in WebView

I work on a Xamarin.Forms app (UWP!). It has a Master-Details architecture. The Master page has a ListView, and each item in it opens a corresponding Detail page. The first Detail page has only a WebView that plays a YouTube video upon loading. The second Detail view has just a placeholder label for now.
Where I switch from first Detail page to the second, the sound of the video from the first Detail page is still heard. And when I switch back to the first Detail page, the video loads again, and now I hear two voices. How can I stop the video upon switching to the second Detail page and resume when going back? If this is not possible, how can I just stop the video upon leaving its Detail page?
I guess I could do something in an overridden OnDisappearing() method of the detail page:
protected override void OnDisappearing()
{
MyWebView.NavigateToString(""); // This does not work, as NavigateToString() is not part of WebView.
base.OnDisappearing();
}
What can I use to stop playing video in WebView?
Could you please tell what I can use to stop playing video in WebView?
For your requirement, you could approach with injecting Eval java script.
private void Button_Clicked(object sender, EventArgs e)
{
string pausefunctionString = #"
var videos = document.querySelectorAll('video');
[].forEach.call(videos, function(video) { video.pause(); });
";
MyWebView.Eval(pausefunctionString);
}
Update
I have re-checked your issue, when you navigate to another page, the WebView has not be released correctly. If you want to stop the WebView video play, you could make it navigate to blank page via custom WebViewRenderer.
[assembly: ExportRenderer(typeof(WebView), typeof(CustomWebViewRender))]
namespace App4.UWP
{
class CustomWebViewRender : WebViewRenderer
{
private Windows.UI.Xaml.Controls.WebView _WebView;
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
var source = Element.Source as UrlWebViewSource;
_WebView = new Windows.UI.Xaml.Controls.WebView();
SetNativeControl(_WebView);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == WebView.SourceProperty.PropertyName)
{
var source = Element.Source as UrlWebViewSource;
if (source.Url == string.Empty)
{
_WebView.NavigateToString(string.Empty);
}
}
}
}
}
Usage
protected override void OnAppearing()
{
base.OnAppearing();
MyWebView.Source = "https://www.youtube.com";
}
protected override void OnDisappearing()
{
MyWebView.Source = string.Empty;
base.OnDisappearing();
}
Xaml
<WebView HeightRequest="500" WidthRequest="500" x:Name="MyWebView"/>

Webview is getting reloaded when app goes into background Xamarin

Everytime when app goes background and comes foreground webview is getting reloaded. I just want to save the state in onpause and reload it when I resume the app.Could it be possible?
I am unable to do that. Any help would be greatly appreciated.
protected override void OnCreate(Bundle bundle)
{
if (bundle == null) { //everytime when I load, bundle is null and url is reloaded
mapWebView.LoadUrl("url");
} else {
mapWebView.RestoreState(bundle);
}
}
protected override void OnResume() {
base.OnResume();
if (mapWebView != null)
mapWebView.OnResume();
}
protected override void OnPause()
{
base.OnPause();
if (mapWebView != null)
{
mapWebView.OnPause();
mapWebView.SaveEnabled = true;
mapWebView.SaveState(bundle) //how to get bundle object here to save state
}
}
mapWebView.SaveState(bundle) //how to get bundle object here to save state
To get Bundle you need to override method
public override void OnSaveInstanceState (Bundle outState, PersistableBundle outPersistentState) {
base.OnSaveInstanceState (outState, outPersistentState);
}
Everytime when app goes background and comes foreground webview is getting reloaded. I just want to save the state in onpause and reload it when I resume the app.
From your question it's hard to understand when you want to reload webview. Because onPause and OnResume will be called every time your app goes background/foreground.

Getting exception when clicking the back button in blackberry

From my application, i am going to the Blackberry Native Message Application to send mail.
when i am clicking the back button, it is giving Runtime Exception.
My code is below:
public void fieldChanged(Field field, int context)
{
if( field == m_lfMailId)
{
displayEmail();
}
}
private void displayEmail()
{
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(MessageArguments.ARG_NEW,"feedback#merucabs.com","",""));
Address toList[] = new Address[1];
}
We usually set the simulator to ignore Error 104 - start fledge with the flag /ignore-error=104. This should not be showing on a real device, you can see some more information in this thread. If you click continue on the simulator's white screen, does it continue alright?
Add this code below to your screen and click on back button.
public boolean onClose()
{
return super.onClose();
}

Windows forms window starting up out of focus (and behind executable folder)

I'm getting some strange behaviour in the start-up of a Windows app and wondered if anyone could throw any light on what is happening and how to get around it.
The problem is with the start-up of the app - it should show a splash screen then a login form. The code for this is:
[STAThread]
static void Main()
{
Application.ThreadException += Application_ThreadException;
MainForm mainForm = null;
Thread splashThread = new Thread(ShowSplash);
try
{
// set up app
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Splash screen
Splash splash = new Splash();
splashThread.Start(splash);
// enable logging
log4net.Config.XmlConfigurator.Configure();
// Create main form
mainForm = new MainForm();
// kill splash
HideForm(splash);
splashThread.Abort();
}
catch (Exception e)
{
splashThread.Abort();
MessageBox.Show(e.Message, "An exception occurred: ", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(0);
}
// start
Login login = new Login();
login.Show();
if (!mainForm.IsDisposed)
{
Application.Run(mainForm);
}
}
static void ShowSplash(object splash)
{
if (!(splash is Splash))
throw new ArgumentException("Splash screen is of wrong type.");
Splash splashForm = (Splash) splash;
splashForm.ShowDialog();
}
// Thread safe hide form
private delegate void HideFormCallback(Form form);
private static void HideForm(Form form)
{
if (form == null || form.IsDisposed)
return;
if (form.InvokeRequired)
{
HideFormCallback d = HideForm;
form.Invoke(d, new object[] { form });
}
else
{
form.Hide();
}
}
So, we're starting up a new thread with the splash screen, setting up the rest of the app in the meantime, then killing the splash screen just before showing the login form.
The problem I'm having is that the login form doesn't have focus when the app starts. The splash screen pops up and goes away as expected. The login form pops up in front of any open windows but doesn't have focus - the folder containing the executable (that I double-clicked to launch) still has focus even when it's behind the login form.
If I comment out all the lines to do with the splash screen, the login form has focus when it appears.
My guess would be that the focus reverts back to the executable folder when the splash screen is hidden but I don't know why the login form doesn't get focus when it launches.
Calling .Focus() on the login form returns null so doesn't work.
Neither form have TopMost or such set on them.
If anyone has any suggestions for what's going on, it would be much appreciated.
This is what I've ended up doing as a somewhat hacky fix:
void LoginView_Shown(object sender, EventArgs e)
{
SetForegroundWindow(Handle);
this.BringToFront();
Activate();
}
[DllImport("user32")]
public static extern int SetForegroundWindow(IntPtr hwnd);

Resources