I've been looking for a solution to my problem for days with no luck. Can someone please take a look:
- Input: a WebView with a web already loaded.
- Output: change the font of the loaded web inside the WebView.
Here's what I've tried so far:
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl("http://www.bbc.co.uk/");
And here's how I attempted to change the font inside the webview: 1/ Method 1:
mWebView.loadUrl("javascript:(function() { var s=document.createElement('style');s.innerHTML ="
+ " '@font-face{font-family:ZawGyi-One;src:url(\"http://db.tt/OQ1RZoWc\");}"
+ "body,div,h1,h2,h3,input,textarea{font-family:ZawGyi-One! important;}';"
+ "document.getElementsByTagName('head')[0].appendChild(s);document.getElementsByTagName('body')[0].style.fontFamily = \"ZawGyi-One\"})()");
2/ Method 2:
mWebView.loadDataWithBaseURL(
null,
"<script>javascript:(function() { var s=document.createElement('style');s.innerHTML ="
+ " '@font-face{font-family:ZawGyi-One;src:url(\"http://db.tt/OQ1RZoWc\");}"
+ "body,div,h1,h2,h3,input,textarea{font-family:ZawGyi-One! important;}';"
+ "document.getElementsByTagName('head')[0].appendChild(s);document.getElementsByTagName('body')[0].style.fontFamily = \"ZawGyi-One\"})() </script>",
"text/html", "UTF-8", null);
3/ Method 3:
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
mWebView.loadUrl("javascript:(function() { var s=document.createElement('style');s.innerHTML ="
+ " '@font-face{font-family:ZawGyi-One;src:url('file:///android_asset/fonts/BLKCHCRY.TTF');}"
+ "body,div,h1,h2,h3,input,textarea{font-family:ZawGyi-One! important;}';"
+ "document.getElementsByTagName('head')[0].appendChild(s);document.getElementsByTagName('body')[0].style.fontFamily = \"ZawGyi-One\"})()");
}
});
Unfortunately, none of my solutions seem to work. I've tried changing the HTML file inside the /assets/ folder and the fonts are stored in /assets/fonts/ folder, but I can't seem to get it right.
**One more thing: Can the font style really be changed inside an already loaded site in a webview? Can someone please guide me.
Thank you for your help.