Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting CSS into webpage in android webview

I was browsing a lot of webpages to get a tutorial. I saw a lot of posts about injecting CSS / js into local HTML file. But I'm trying to inject my CSS file into the webpages in android webview project. Example: injecting custom font CSS into Facebook, Google, etc... (Not into local HTML file). My codes are not working.

This are my code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);
    String html = "<html><head><style>@font-face {@font-family: 'Conv_LISU'; src: url('file:///android_asset/font/LISU.ttf');} body, button, input, label, select, td, tr, textarea,li,ul,span,div,table,h1,h2,h3,h4{ font-family:Conv_LISU;}</style></head>";

    WebView webView = (WebView)findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
            // Handle the error
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });

    webView.setInitialScale(1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.loadData(html, "text/html", "utf-8");
    webView.loadUrl("http://google.com");


}

}

like image 246
Gwa Si Avatar asked Nov 22 '25 08:11

Gwa Si


1 Answers

This way does not work because your source font is coming from /assets/ folder.

    String html = "<html><head><style>@font-face {@font-family: 'Conv_LISU'; src: url('file:///android_asset/font/LISU.ttf');} body, button, input, label, select, td, tr, textarea,li,ul,span,div,table,h1,h2,h3,h4{ font-family:Conv_LISU;}</style></head>";

CSS shall not get font when it is not coming from internet, change your code at "src:url('file:///android_asset/font/LISU.ttf')" to some downloadable font link, like: "src:url("http://www.vonna.com/fonts/sahara01.ttf")".

It should work now.

like image 153
zoro Avatar answered Nov 24 '25 21:11

zoro