How to set base URL while loading an URL to the WebView

3.7k views Asked by At

I am using WebView with the need of providing an access from HTML to javascript file located in raw resources. I can simply do it while loading HTML page from data with:

webView.loadDataWithBaseURL("file:///android_res/raw/", getHtml(), "text/html", "utf-8", null);


This way a call in loaded HTML

<script type="text/javascript" src="mraid.js"></script> 

leads to mraid.js located under res/raw folder.

Question is, is there an easy way to set the base URL similarly while loading the page from external URL to achieve same effect? Unfortunatelly I see no kind of WebView.loadUrlWithBaseUrl method.

Do I have to get the page with HTTP GET and than use `loadDataWithBaseURL' method like above?

2

There are 2 answers

0
marcin.kosiba On BEST ANSWER

I don't think there is an easy way to set the base url. If you control the server you could just make it possible to specify an extra param that will add a <base href="file:///android_res/raw/" /> tag.

Otherwise you could use shouldInterceptRequest to serve a local resource instead of a remote one. (NOTE: mind the threads!)

0
yuva ツ On

Try this-

  mWebview =(WebView)findViewById(R.id.webviewNews);
            mWebview.getSettings().setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
            mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
            mWebview.getSettings().setAppCacheEnabled(true); 
            mWebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            mWebview.getSettings().supportZoom();
            mWebview.canGoBack();
            mWebview.loadUrl("http://www.google.com/");