2012-01-05 59 views

回答

1
String html = ... // load manually 
// insert the style to <head> 
webview.loadData(html, "text/html", null); 
+0

您能詳細好嗎? – 2016-09-12 13:34:27

+0

@ An-droid例如:String html = download(「http://www.stackoverflow.com」); html = html.replaceFirst(「」,「」); webview.loadData(html,「text/html」,null); – xfx 2016-09-13 20:29:55

1

您可以通過使用javascript: URL能力注入自定義JS 。

下面是你可以從Java添加使用該CSS規則:

/** 
* Creates a CSS element in the <head> section of the Web page and assigns it 
* to a `customSheet` JS variable 
*/ 
private final static String CREATE_CUSTOM_SHEET = 
    "if (typeof(document.head) != 'undefined' && typeof(customSheet) == 'undefined') {" 
     + "var customSheet = (function() {" 
      + "var style = document.createElement(\"style\");" 
      + "style.appendChild(document.createTextNode(\"\"));" 
      + "document.head.appendChild(style);" 
      + "return style.sheet;" 
     + "})();" 
    + "}"; 

/** 
* Adds CSS properties to the loaded Web page. A <head> section should exist when this method is called. 
* The Web view should be configured with `.getSettings().setJavaScriptEnabled(true);` 
* 
* @param webView Web view to inject into 
* @param cssRules CSS rules to inject 
*/ 
void injectCssIntoWebView(WebView webView, String... cssRules) { 
    StringBuilder jsUrl = new StringBuilder("javascript:"); 
    jsUrl 
     .append(CREATE_CUSTOM_SHEET) 
     .append("if (typeof(customSheet) != 'undefined') {"); 
    int cnt = 0; 
    for (String cssRule : cssRules) { 
     jsUrl 
      .append("customSheet.insertRule('") 
      .append(cssRule) 
      .append("', ") 
      .append(cnt++) 
      .append(");"); 
    } 
    jsUrl.append("}"); 

    webView.loadUrl(jsUrl.toString()); 
} 

下面是上述方法的使用示例:

@Override 
public void onPageFinished(WebView webView, String url) { 
    // Several people probably worked hard on the design of this Web page, let's hope they won't see what's next 
    injectCssIntoWebView(
     webView, 
     "div { border: 4px solid yellow; }", 
     "p { border: 4px solid green; }", 
     "a { border: 4px solid black; }", 
     "img { border: 4px solid blue; }" 
    ); 
} 
相關問題