Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inject CSS to a site with webview in android

For example I want to change the background-color of www.google.comto red. I have used webview, and my style.cssfile is in assest folder. I want to inject this style.css file to www.google.com. What is wrong with my codes? Please write the correct codes for me. Thanks. My MainActitviy.java file :

package com.example.mysina;  import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView;  public class MainActivity extends ActionBarActivity {           @Override         protected void onCreate(Bundle savedInstanceState) {             super.onCreate(savedInstanceState);             setContentView(R.layout.activity_main);             WebView webView = new WebView(this);              setContentView(webView);                      String html = "<html><head><style> src: url('file:///android_asset/style.css')</style></head></html>";                      webView.loadData(html, "text/html", "utf-8");                     webView.loadUrl("https://www.google.com");         }         @Override         public boolean onCreateOptionsMenu(Menu menu) {             // Inflate the menu; this adds items to the action bar if it is present.             getMenuInflater().inflate(R.menu.main, menu);             return true;         }          @Override         public boolean onOptionsItemSelected(MenuItem item) {             // Handle action bar item clicks here. The action bar will             // automatically handle clicks on the Home/Up button, so long             // as you specify a parent activity in AndroidManifest.xml.             int id = item.getItemId();             if (id == R.id.action_settings) {                 return true;             }             return super.onOptionsItemSelected(item);         }     } 
like image 515
sinaamiri Avatar asked May 03 '15 19:05

sinaamiri


People also ask

How do I load CSS in WebView?

Double-click the “src” folder in your Android project. Double-click the package containing the WebView Activity then double-click the Activity to open it in the editor. Click inside the “onCreate” method to begin typing there.

How do I display HTML content in WebView?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken web view to show html content.

Is it possible to get data from HTML forms into Android while WebView?

Yes you can, you can use javascript to get webpage content. Then use the webview jsInterface to return the content to you java code.

Do cookies work in WebView?

By default this is set to true and the WebView accepts cookies.


2 Answers

You can't inject CSS directly however you can use Javascript to manipulate page dom.

public class MainActivity extends ActionBarActivity {    WebView webView;    @Override   protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);      webView = new WebView(this);     setContentView(webView);      // Enable Javascript     webView.getSettings().setJavaScriptEnabled(true);      // Add a WebViewClient     webView.setWebViewClient(new WebViewClient() {          @Override         public void onPageFinished(WebView view, String url) {              // Inject CSS when page is done loading             injectCSS();             super.onPageFinished(view, url);         }     });      // Load a webpage     webView.loadUrl("https://www.google.com"); }  // Inject CSS method: read style.css from assets folder // Append stylesheet to document head private void injectCSS() {     try {         InputStream inputStream = getAssets().open("style.css");         byte[] buffer = new byte[inputStream.available()];         inputStream.read(buffer);         inputStream.close();         String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);         webView.loadUrl("javascript:(function() {" +                 "var parent = document.getElementsByTagName('head').item(0);" +                 "var style = document.createElement('style');" +                 "style.type = 'text/css';" +                 // Tell the browser to BASE64-decode the string into your script !!!                 "style.innerHTML = window.atob('" + encoded + "');" +                 "parent.appendChild(style)" +                 "})()");     } catch (Exception e) {         e.printStackTrace();     } }  @Override public boolean onCreateOptionsMenu(Menu menu) {     // Inflate the menu; this adds items to the action bar if it is present.     getMenuInflater().inflate(R.menu.main, menu);     return true; }  @Override public boolean onOptionsItemSelected(MenuItem item) {     // Handle action bar item clicks here. The action bar will     // automatically handle clicks on the Home/Up button, so long     // as you specify a parent activity in AndroidManifest.xml.     int id = item.getItemId();     if (id == R.id.action_settings) {         return true;     }     return super.onOptionsItemSelected(item);   } } 
like image 101
Manish Avatar answered Sep 21 '22 14:09

Manish


I was able to inject css by using "evaluateJavascript" which was added to WebView in API 19 https://developer.android.com/reference/android/webkit/WebView

Example in Kotlin:

private lateinit var webView: WebView  override fun onCreate(savedInstanceState: Bundle?) {      super.onCreate(savedInstanceState)      //...      webView = findViewById(R.id.your_webview_name)      webView.settings.javaScriptEnabled = true      webView.webViewClient = object : WebViewClient() {          override fun onPageFinished(view: WebView, url: String) {              val css = ".menu_height{height:35px;}.. etc..." //your css as String             val js = "var style = document.createElement('style'); style.innerHTML = '$css'; document.head.appendChild(style);"             webView.evaluateJavascript(js,null)             super.onPageFinished(view, url)         }     }      webView.loadUrl("https://mywepage.com") //webpage you want to load    } 

UPDATE: The code above had issues applying all of the injected CSS. After consulting with my web developer, we decided to inject the link to the CSS file instead of the CSS code itself. I changed the values of the css and js variables ->

val css = "https://mywebsite.com/css/custom_app_styles.css" val js = "var link = document.createElement('link'); link.setAttribute('href','$css'); link.setAttribute('rel', 'stylesheet'); link.setAttribute('type','text/css'); document.head.appendChild(link);" 
like image 23
iOS_Mouse Avatar answered Sep 19 '22 14:09

iOS_Mouse