Vahid Amiri
Vahid Amiri

Reputation: 11117

Injecting JavaScript into WebView in Android 6

So recently I was trying to build my app for Android 6 by setting the android:targetSdkVersion="23" in the manifest file, everything went well but then I noticed the strange behavior of webview.

In my app I first load some content into the webview using the webview.LoadData (someHtmlContent, "text/html; charset=UTF-8", null); then at any point user can change the text size by using some buttons in the menu of the app. These buttons work like this:

webview.LoadUrl ("javascript:" + "document.getElementsByTagName(\"body\")[0].style.fontSize = \"" + size + "%\";");

size is a string that can be anything from 100% (Initial size) to 110%, 120% and ...

This method effectively injects JavaScript into the already existing content (HTML) and works perfectly on Android 5 and lower but not on Android 6.

In Android 6, when user clicks a button that injects JS, it just replaces the content of webview with the size variable.

Can anyone help?

Upvotes: 1

Views: 1584

Answers (1)

Vahid Amiri
Vahid Amiri

Reputation: 11117

I don't know why LoadUrl method of webview didn't work but I just found out about a new method EvaluateJavascript that should be used for Android 4.4 and up. I just tested this with my app (Android 6) and it works fine.

So, the following code should be used instead: (I'm using C#/Xamarin)

if ((int)Build.VERSION.SdkInt >= 19)
{
    webview.EvaluateJavascript ("document.getElementsByTagName(\"body\")[0].style.fontSize = \"" + size + "%\";", null);
}
else
{
    webview.LoadUrl ("javascript:" + "document.getElementsByTagName(\"body\")[0].style.fontSize = \"" + size + "%\";");
}

Here there's a Java Example.

Upvotes: 1

Related Questions