7

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 ?

1
  • You want t change the background color of Webview ? If yes, then you can try using setBackgroundcolor as well. Sep 1, 2013 at 4:31

1 Answer 1

8

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);       
    }
}
2
  • thanks turns out it was my javascript that was the issue and i changed it as per your provided link. can you upvote my question i dont know why its voted down.
    – j2emanue
    Sep 1, 2013 at 14:44
  • 1
    Glad it worked out. I upvoted it. I think it was voted down because you haven't tried your javascript code in a browser and posted the question as an Android, while it had a javascript issue. Sep 1, 2013 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.