Android WebViewClient onPageStarted attach javascript listener or preprocess html -
i looking implement behavior in android mirror ios , windows based product. put need attach javascript listener custom event fire android java function. listener must attached before script tags in head element of html document processed. (an event fired in scripts statically provided via document in head element need listen for)
an example html page:
<!doctype html> <html> <head> <script> // // fire custom event message var message = 'ice cream tornado'; var event = new customevent('messagetoandroid', {'detail': json.stringify(message)}); window.dispatchevent(event); </script> </head> <body> <p>lets pretend login page</p> </body> </html>
so above intention send message: 'ice cream tornado' custom javascript event 'messagetoandroid'
is there way add header element following javascript before header processed, , above current script tag:
<script>window.addeventlistener('messagetoandroid',function(event){ window.jsinterface.listenerformessages(event.detail);});</script>
my current efforts have failed attempting use onpagestarted():
webview.setwebviewclient(new webviewclient() { @override public void onpagestarted(webview view, string url, bitmap favicon) { super.onpagestarted(view, url, favicon); view.evaluatejavascript("window.addeventlistener('messagetoandroid',function(event){ window.jsinterface.listenerformessages(event.detail);});", null); }
however within same function can cause javascript write console, , call window.jsinterface.listenerformessages('test') without issue. i'm missing something, perhaps window variable cleared out after onpagestart. believe have ruled out timing issue (since evaluate async) because adding bunch of console logs place .javascriptevaluates occur in onpagestarted being run before html processed.
i prefer stay clear of doing url request pull data down, modify html, load data webview, since page points needs socket based communication (and i'm not sure if workaround interfere in fashion). seems should able this, suggestions appreciated.
as aside, receiving error believe related attempt @ attached listener:
e/chromium: [error:interface_registry.cc(99)] failed locate binder interface: autofill::mojom:autofilldriver
Comments
Post a Comment