2

I use following code to load page to MyWebView:

private void DisplayLocalPage(string filename)
{
    var html = new HtmlWebViewSource();
    html.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
    html.Html = ReadFile(filename);
    MyWebView.Source = html;
    MyWebView.Eval("alert(200)");
}

Page is rendered well - all scripts run too, but this alert isn't fired, what are possible reasons?

5
  • You should allow the permission to run scripts. Does it work if you write it in the document ready event of JS of the loaded page? Commented Aug 3, 2016 at 10:38
  • I put the alert in onload of body and it works. Commented Aug 3, 2016 at 10:42
  • Check out this link : tipsabc.com/2016/… Commented Aug 3, 2016 at 10:46
  • wait, according to this: developer.xamarin.com/recipes/cross-platform/xamarin-forms/… there is no need to create custom renderers and so on, why then? Commented Aug 3, 2016 at 10:52
  • Its only required if you need some advanced options, also there is an ExtendedWebView by XLabs. Apart from that with this piece of code its hard to explain further. Commented Aug 3, 2016 at 10:58

2 Answers 2

3

Please try this:

webView.Navigated += (o, s) => {
     webView.Eval("alert('text')");
     };
Sign up to request clarification or add additional context in comments.

4 Comments

an explanation of your solution is usually helpful
@happymacarts the explanation is in my answer.
Both @Kamil Smrčka and cuddlecheek are correct. The reason the JavaScript isn't firing is because the page hasn't finished loading. The description from the documentation (developer.xamarin.com/api/event/Xamarin.Forms.WebView.Navigated) for the Navigated event is: "Event that is raised after navigation completes." So in the above answer Kamil is subscribing to the Navigated event (in this case the page load complete event) and executing his JavaScript after it fires.
@JohnLay That still does not work for me. No alert is displayed.
0

I think I figured out why it might not work. The Eval is triggered before the WebView is fully initialized or web page is rendered, so the script is trigerred, but doesn't have any effect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.