Search code examples
androidwebviewxamarin.formsjavascript-injection

Javascript Injection with Xamarin forms WebView


I want to change the value of an element inside a Xamarin forms WebView

I created a new project and added a WebView page that loads https://www.google.com/
I have used .Eval

m_GoogleWebView.Eval("alert('coolness!');");

This alerts fine for me. However if I try to access the dom at all, it just replaces the WebView with the text 'test text'

m_GoogleWebView.Eval("document.getElementById('lst-ib').value='test text';");

How should I manipulate elements from Xamarin Forms?


Solution

  • This is an issue with any WebView on Android after 4.1.

    What you need to do, is assign your script to a variable like this

    m_GoogleWebView.Eval("var x = document.getElementById('lst-ib').value='test text';");
    

    This still runs the script but now just assigns the result to the variable instead of the DOM.