Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - after loading URL with webview can i change background color

I have a webview and im loading an external HTML form a site. I try to change the background color using javascript function:

    function changeBGC(color){
document.bgColor = color;
}

and that does not work. but if i load locally then im able to change the background color. Is there some kind of security inhibiting me from changing a web page i load into the webview externally ?

like image 545
j2emanue Avatar asked Sep 01 '13 04:09

j2emanue


People also ask

How do I change the background color in WebView?

webview. setBackgroundColor(getContext(). getResources(). getColor(android.

Can I change web page background color?

Change the Background Color of a Web Page Right-click the page to which you want to change a background color, and then click Page Properties. Click the Formatting tab. Click the Background list arrow. Click the color you want on the color palette.


1 Answers

You can run javascript using the WebViewClient, example here.

The javascript code that changes the background color of a document.

So to put it all together:

When initing WebView:

WebView webview = new WebView();
webview.setWebViewClient(new WebClient());
webView.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("stackoverflow.com");

Your web view client:

public class WebClient extends WebViewClient {

    int color;

    public WebClient(int color) {
        this.color = color;
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) 
    {
        String command = "javascript:document.body.style.background = " + color + ";";
        view.loadUrl(command);       
    }
}
like image 76
Andras Balázs Lajtha Avatar answered Nov 06 '22 20:11

Andras Balázs Lajtha