I am experimenting displaying some 3D scenes through a WebView in Android using ThreeJS, and it is working fine except when it comes to interacting with the web layer and calling functions defined in it.
I need to call a JS function from within Android code when a pager is scrolled. I am achieving this with:
LaunchedEffect(key1 = pagerState) {
snapshotFlow { pagerState.currentPage }.collect { page ->
println("Android: Page selected $page")
webView?.evaluateJavascript("onPageSelected($page);", null)
//webView?.loadUrl("javascript:onPageSelected($page);")
}
}
This unfortunately doesn’t work, I get this error:
[INFO:CONSOLE(1)] "Uncaught ReferenceError: onPageSelected is not defined", source: http://192.168.0.15:5173/ (1)
I tried both evaluateJavascript and the commented-out loadUrl and none of them work.
This is how my WebView is setup. I think everything is OK because the 3D is rendering as expected
AndroidView(
factory = { context ->
WebView(context).apply {
settings.apply {
javaScriptEnabled = true
javaScriptCanOpenWindowsAutomatically = true
domStorageEnabled = true
}
webViewClient = CustomWebViewClient().apply {}
loadUrl("http://192.168.0.15:5173/")
}
},
update = { webView = it },
modifier = modifier
)
And this is the HTML + JS code being displayed in the WebView:
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - lights - point lights</title>
<meta charset="utf-8">
<meta content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"
name="viewport">
<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js",
"three/addons/": "./jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import Stats from 'three/addons/libs/stats.module.js';
import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';
let camera, scene, renderer,
light1, light2, light3, light4,
object, stats;
const clock = new THREE.Clock();
init();
animate();
onPageSelected(0);
function init() {
camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 100;
scene = new THREE.Scene();
//model
const loader = new OBJLoader();
//const objPath = 'models/obj/walt/WaltHead.obj'
const objPath = 'models/obj/male02/male02.obj'
loader.load(objPath, function ( obj ) {
object = obj;
object.scale.multiplyScalar( 0.8 );
object.position.y = - 30;
scene.add( object );
} );
const sphere = new THREE.SphereGeometry( 0.5, 16, 8 );
//lights
light1 = new THREE.PointLight( 0xff0040, 400 );
light1.add( new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xff0040 } ) ) );
scene.add( light1 );
light2 = new THREE.PointLight( 0x0040ff, 400 );
light2.add( new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0x0040ff } ) ) );
scene.add( light2 );
light3 = new THREE.PointLight( 0x80ff80, 400 );
light3.add( new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0x80ff80 } ) ) );
scene.add( light3 );
light4 = new THREE.PointLight( 0xffaa00, 400 );
light4.add( new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xffaa00 } ) ) );
scene.add( light4 );
//renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//stats
stats = new Stats();
document.body.appendChild( stats.dom );
window.addEventListener( 'resize', onWindowResize );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
const time = Date.now() * 0.0005;
const delta = clock.getDelta();
if ( object ) object.rotation.y -= 0.5 * delta;
light1.position.x = Math.sin( time * 0.7 ) * 30;
light1.position.y = Math.cos( time * 0.5 ) * 40;
light1.position.z = Math.cos( time * 0.3 ) * 30;
light2.position.x = Math.cos( time * 0.3 ) * 30;
light2.position.y = Math.sin( time * 0.5 ) * 40;
light2.position.z = Math.sin( time * 0.7 ) * 30;
light3.position.x = Math.sin( time * 0.7 ) * 30;
light3.position.y = Math.cos( time * 0.3 ) * 40;
light3.position.z = Math.sin( time * 0.5 ) * 30;
light4.position.x = Math.sin( time * 0.3 ) * 30;
light4.position.y = Math.cos( time * 0.7 ) * 40;
light4.position.z = Math.sin( time * 0.5 ) * 30;
renderer.render( scene, camera );
}
function onPageSelected(page) {
console.log("hello world " + page);
}
</script>
</body>
</html>
Interesting observation:
The onPageSelected(0); called from within the JS code itself works as expected and I get this logged:
[INFO:CONSOLE(122)] "hello world 0", source: http://192.168.0.15:5173/index.html?html-proxy&index=0.js (122)
It’s curious that the “source” is different than the function call that failed.
Another interesting thing is that if I move the function definition out of this
<script type="module"> block, into it’s own <script> block, it works! But I need it to be in that block because I need it to alter a variable that is used during 3D rendering.
So my assumption is that this type="module" thing is changing the visibility of the function and preventing it from being accessible from Android. I found a similar unanswered question from years ago with the same problem: Android Webview evaluateJavascript not able to find function inside a ES6 module file
I wonder what can be done to fix it?