在Android中使用webview将网站注入CSS

sin*_*iri 27 css android webkit webview

例如,我想将背景颜色更改www.google.comred.我用过webview,我的style.css档案在assest folder.我想将此style.css文件注入www.google.com.我的代码出了什么问题?请为我写正确的代码.谢谢.我的MainActitviy.java档案:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Man*_*Raj 48

你不能直接注入CSS,但你可以使用Javascript来操作页面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);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么选择base64? (3认同)
  • @Vishal您介意在这里添加您正在谈论的内容吗? (2认同)

iOS*_*use 11

我能够使用“evaluateJavascript”注入CSS,该“evaluateJavascript”已添加到API 19中的WebView https://developer.android.com/reference/android/webkit/WebView

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   
}
Run Code Online (Sandbox Code Playgroud)

更新:上面的代码在应用所有注入的 CSS 时出现问题。在咨询了我的 Web 开发人员后,我们决定将链接注入CSS文件而不是 CSS 代码本身。我更改了 css 和 js 变量的值 ->

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);"
Run Code Online (Sandbox Code Playgroud)