Monday, December 24, 2018

How to use Custom CSS/Javascript in Android WebView


By default you cannot get custom CSS/Javascript loaded into Android Webview. We should override the onPageFinished method to be able to add custom CSS/javascript to Android Webview.





This example is using Kotlin, you may search something else if you're using native Java code or Flutter.





The best approach to use Custom CSS/Javascript is by creating the style node containing CSS and a script node containing the javascript for your sites.





var node = document.createElement('style');

node.type = 'text/css';
node.innerHTML = 'MY_CSS_STYLE';

document.head.appendChild(node);




and





var node = document.createElement('script');

node.type = 'text/javascript';
node.innerHTML = 'MY_JS_SCRIPT';

document.body.appendChild(node);




and override the onPageFinished method:





override fun onPageFinished(view: WebView, url: String) {
val code = """javascript:(function() {

var node = document.createElement('style');

node.type = 'text/css';
node.innerHTML = 'body {
color: white;
background-color: black;
}';

document.head.appendChild(node);

})()""".trimIndent()

loadUrl(code)
}





0 comments:

Post a Comment