Сначала фрагментный хостинг код duktape: < /p>
val duktape = Duktape.create()
// Bind the RetrofitBridge instance to Duktape
val webView = binding.unvisibleWebview
val retrofitBridge = RetrofitBridge(webView)
duktape.set("retrofitBridge", AndroidNetworking::class.java, retrofitBridge)
try {
// Execute JavaScript code
val jsCode = """var result = retrofitBridge.webViewRequest("https://jsonplaceholder.typicode.com/posts"); result; // Return the result to Kotlin"""
val result = duktape.evaluate(jsCode)
Log.d("ResponseHtml", result.toString())
println(result) // Print the output
} catch (e: Exception) {
e.printStackTrace()
} finally {
duktape.close() // Clean up resources
}
- Сетевой интерфейс Duktape Android:
fun getRequest(url: String): String
fun postRequest(url : String): String
fun webViewRequest(url: String): String
}
< /code>
- Реализация WebViewRequest: < /li>
< /ol>
override fun webViewRequest(url: String): String {
var resultHtml: String? = null
WebViewClientRequest(webView, url) { html ->
resultHtml = html
}
return resultHtml ?: ""
}
Класс WebViewClientRequest:
private val webView: WebView,
private val url: String,
) {
init {
val webSettings = webView.settings
webSettings.javaScriptEnabled = true
webSettings.userAgentString =
"Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36"
val cookieManager = CookieManager.getInstance()
cookieManager.setAcceptCookie(true)
cookieManager.setAcceptThirdPartyCookies(webView, true)
webView.addJavascriptInterface(JsInterface(), "HTMLOUT")
webView.webViewClient = WebClientFetchData()
webView.loadUrl(url)
}
inner class WebClientFetchData : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
// Inject JavaScript to fetch the HTML content
webView.loadUrl(
"javascript:window.HTMLOUT.showHTML(''+document.getElementsByTagName('html')[0].innerHTML+'');"
)
}
override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
super.onReceivedError(view, request, error)
println("Error loading page: $error")
}
}
inner class JsInterface {
@JavascriptInterface
fun showHTML(html: String) {
println(html)
}
}
}
Я хочу реализовать, чтобы не возвращать webViewRequest до тех пор, пока DOM не будет очищен без изменения webViewRequest для приостановки функции для работы с dukeTape
Я пытался использовать runBlocking, бесполезно, также я попробовал следующее, но не могу передать данные в DukTape
runBlocking {
WebViewClientRequest(webView, url) { html ->
resultHtml = html
}
}
CoroutineScope(Dispatchers.Main).launch {
WebViewClientRequest(webView, url) { html ->
resultHtml = html
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... coroutines
Мобильная версия