AndreiBogdan AndreiBogdan - 5 months ago 17
Android Question

Inject <link> and <script> in webview

@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);

view.loadUrl("javascript: function(){" +
"var newlink = document.createElement('link');" +
"newlink.setAttribute('rel', 'stylesheet');" +
"newlink.setAttribute('href', 'http://maven.com/slide/caca.css');" +
"document.getElementsByTagName('head').item(0).appendChild(newlink);" +
"}");

}


But the thing won't run ok. I was expecting for the webview to download the CSS and set in to the page.

Basically I want to add remote CSS and JS files to a webview.

Any ideas on how I could accomplish this? I really don't want to manually download the content of the files, cache them or whatnot, and then set them in the webview.

Answer

Apparently this works. Not entirely sure why though ...

        view.loadUrl("javascript:(function() { "

            + "var script=document.createElement('link'); "
            + " script.setAttribute('type','text/css'); "
            + " script.setAttribute('rel','stylesheet'); "
            + " script.setAttribute('href', 'http://maven.com/slide/caca.css'); "
            + "document.head.appendChild(script); "

            + "})();");

Anyway ... 7 hours right down the drain ...