implement img extraction using js evaluating on webview

This commit is contained in:
mykola2312 2024-07-16 02:53:47 +03:00
parent 478acb5f9e
commit 75a637caf6
2 changed files with 24 additions and 1 deletions

View file

@ -1,7 +1,10 @@
package com.mykola2312.outagefetch
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import android.webkit.ValueCallback
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
@ -14,6 +17,7 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.viewinterop.AndroidView
import com.mykola2312.outagefetch.ui.theme.OutageFetchTheme
@ -35,9 +39,10 @@ class MainActivity : ComponentActivity() {
}
}
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun ExtractWebView() {
val url = "https://2ip.ua"
val url = stringResource(id = R.string.fetch_url)
AndroidView(factory = {
WebView(it).apply {
@ -45,17 +50,34 @@ fun ExtractWebView() {
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
this.webViewClient = ExtractorClient()
}
}, update = {
it.settings.javaScriptEnabled = true
it.loadUrl(url);
})
}
class ExtractorClient : WebViewClient() {
companion object ExtractConstants {
const val JS_EXTRACT = "document.getElementsByClassName(\"aos-init aos-animate\").item(0).children[4].lastChild.src";
}
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
return false
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
view?.evaluateJavascript(JS_EXTRACT, ValueCallback<String> {
if (it != null) {
val scheduleImgUrl = it.removeSurrounding("\"")
Log.i("extract", scheduleImgUrl)
}
})
}
}
@Composable

View file

@ -1,3 +1,4 @@
<resources>
<string name="app_name">OutageFetch</string>
<string name="fetch_url">https://poweron.loe.lviv.ua/</string>
</resources>