I'm loading a webpage within a WebView and trying to subscribe to JS events. As an example, let's say I'm looking for the window 'load' event.
I configure the webview in its onFinishInflate
:
webView.setJavaScriptEnabled(true);
webView.loadUrl("javascript:window.addEventListener('load', function(){alert('loaded');})");
I assume this registration persists across page navigations and that it can be made before any page is actually loaded (due to being done on window
).
When loading any url following that, such as webView.loadUrl("https://www.google.com")
, no alert shows up.
I have also tried loading that javascript string as a url in the web view client's onPageStarted
& onPageFinished
. No difference.
Is it possible to subscribe to a web view's window events? Eventually, I plan on using the @JavascriptInterface
pattern to call back into the native code when the JS event occurs. I would like to avoid having the web page itself know about the injected Java/JS object (having to verify the existence of this bridge object before calling a method on it seems sloppy– I find the event bus pattern cleaner here).