I am trying to create an app that programmatically fills a form and submits it while being in the background...
I have implemented it with web_view and it works perfectly but it's in an Activity but I want to do the same thing from the background.
As the web view is a UI element I don't know how to run it in a worker!
My code (works only when the app is open):
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// Calling the composable function
// to display element and its contents
MainContent()
}
}
}
// Creating a composable
// function to display Top Bar
@Composable
fun MainContent() {
Scaffold(
topBar = { TopAppBar(title = { Text("WebView", color = Color.White) }, backgroundColor = Color(0xff0f9d58)) },
content = { MyContent() }
)
}
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun MyContent(){
val context = LocalContext.current
// Declare a string that contains a url
// val mUrl = "http:www.example.com"
// Adding a WebView inside AndroidView
// with layout as full screen
AndroidView(factory = {
WebView(it).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
webViewClient = object: WebViewClient(){
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
evaluateJavascript("const inputList=document.querySelectorAll(\"input\");\n" +
"inputList[0].value=\"00000\";\n" +
"inputList[1].value=\"00000\";\n" +
"inputList[2].click()", null)
}
}
settings.javaScriptEnabled = true
loadUrl(mUrl)
//enable javascript
}
}, update = {
it.loadUrl(mUrl)
})
}
// For displaying preview in
// the Android Studio IDE emulator
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MainContent()
}
So my question is:
1. can I run the web-view in a worker (WorkManger) and how?
2. Is there any other way to do this without a web-view?
For my case Htmlunit-android worked perfectly ... It can browse the web in a headless mood and can submit forms.
exlample of form submiton:
private fun submittingForm() {
val webClient = WebClient()
// Get the first page
val page1 = webClient.getPage<HtmlPage>("http://some_url")
// Get the form that we are dealing with and within that form,
// find the submit button and the field that we want to change.
val form = page1.getFormByName("myform")
val button = form.getInputByName<HtmlSubmitInput>("submitbutton")
val textField = form.getInputByName<HtmlTextInput>("userid")
// Change the value of the text field
textField.type("root")
// Now submit the form by clicking the button and get back the second page.
val page2 = button.click<HtmlPage>()
}