WebView with injected JS script

Few months ago my friend asked me if it’s possible to fill the forms without typing on website inside webView? Or even change the whole UI of web page? I didn’t know the answer, but some research led me to solution that is pretty simple, so this article will show you how to achieve it.

We will use JavaScript to change some of the UI properties for google.com website, so the obvious thing we need to do is to allow webView to use JavaScript.

Our JS function is really simple. Using DOM allows to change some of the website properties in few lines of code! In Java we usually use this to read XML files, but if you are not familiar with it - check this tutorial. It is very important to call injectJS() after website is fully loaded, because in this case JS function is based on already created elements of website. However, this does not prevent you from using jQuery or any other JS framework that you are familiar with.

Assuming that JS file is in assets we are able to read it. Thankfully, Kotlin gives possibility to read whole file in one line of code. So, the last step is to load JavaScript function for our website.

Keep in mind that for most cases your changes are applied to mobile version of web page, so inspecting website code on desktop version will not always reflect the mobile one.

Example project is available here.

When such an approach is useful ?

If your app conducts user to fill forms through webView you can use user data which is already in your app to pre-fill those forms with JS script. You also can give a second life to the old, but still useful web page. Simply improve it from UX perspective or just make it look better.

Use this very carefully

Use it mainly for webpages that you control and manage, since injecting code to an existing page is risky and not immune to changes on the web page. When using on other webpages, always remember that this approach is based on a code structure that you have no influence on so you will have a lot of work with maintaining it whenever the target webpage is changed.

You also need to remember that not every solution will work as you need to be prepared for different code approaches, especially if the website is using complex JS scrips or has some minification / obfuscation applied.

If you like my work hit 👏 button and let me know what you think in comments!