I am trying to inject js into the webview. My goal is to inject custom js on the website loaded. I use following code to inject javascript to my simple webview in xamarin forms.
XAML:
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:BrowserApp" x:Class="BrowserApp.Views.BrowserAppPage">
<StackLayout>
<StackLayout Orientation="Horizontal">
<Button Text="<" HeightRequest="40" WidthRequest="40" Clicked="Back_Clicked"/>
<Button Text=">" HeightRequest="40" WidthRequest="40" Clicked="Forward_Clicked"/>
<Entry x:Name="url" WidthRequest="180" />
<Button Text="Go" HeightRequest="40" WidthRequest="50" Clicked="Go_Clicked"/>
</StackLayout>
<Label x:Name="LoadingLabel" IsVisible="false"/>
<WebView x:Name="Browser" HeightRequest="1000" WidthRequest="1000" Navigating="Handle_Navigating" Navigated="Handle_Navigated"/>
</StackLayout>
</ContentPage>
XAML.CS:
using System.Threading.Tasks;
using Xamarin.Forms;
namespace BrowserApp.Views
{
public partial class BrowserAppPage : ContentPage
{
public async void Handle_Navigated(WebView sender, Xamarin.Forms.WebNavigatedEventArgs e)
{
await sender.EvaluateJavaScriptAsync("javascript:alert();");
LoadingLabel.IsVisible = false;
}
void Handle_Navigating(object sender, Xamarin.Forms.WebNavigatingEventArgs e)
{
LoadingLabel.IsVisible = true;
}
void Go_Clicked(object sender, System.EventArgs e)
{
Browser.Source = url.Text;
}
void Forward_Clicked(object sender, System.EventArgs e)
{
if (Browser.CanGoForward)
Browser.GoForward();
}
void Back_Clicked(object sender, System.EventArgs e)
{
if (Browser.CanGoBack)
Browser.GoBack();
}
public BrowserAppPage()
{
InitializeComponent();
url.Text = "https://google.com";
Browser.Source = url.Text;
}
}
}
Somehow the js is not injected. Not even a simple alert works.
Edit: I checked the code on a android device, instead of UWP. On android it is working. Is there a way to enable javascript for the platforms?