How to load a javascript redirect into android webview?

3.7k Views Asked by At

I am trying to load a page into webview. Normally, when i call

webview.loadUrl(url);

it works fine. The url has a javascript code that redirects the page. Here is the jacascript code:

<script type="text/javascript">
        if (!document.cookie || document.cookie.indexOf('AVPDCAP=') == -1)
        { document.write('<scr'+'ipt src="http://some_link_here+Math.floor(89999999*Math.random()+10000000)+'&millis='+new Date().getTime()+'&referrer='+encodeURIComponent(document.location)+'" type="text/javascript"></scr'+'ipt>'); }
</script>

When i try to load that javascript code into my webview like the following:

String data = javascript_code_above;
topBannerWV.loadDataWithBaseURL("", data, "text/html", "UTF-8", null);

where data is this javascript code, it does not load the page. I also tried following:

topBannerWV.loadDataWithBaseURL("", data, "text/javascript", "UTF-8", null);

but this time that text is loaded into webview. Can anyone help me with this?

Thanks.

2

There are 2 best solutions below

0
On BEST ANSWER

I found the solution.

Instead of directly giving the string to webview to load, i first wrote it into a file and then gave that file to webview to load.

 getContext().getApplicationContext().deleteFile("data.html");
 Writer output = null;
 File dir = getContext().getApplicationContext().getFilesDir();
 File file = new File(dir.getAbsolutePath() + File.separator + "data.html");
 file.createNewFile();
 output = new BufferedWriter(new FileWriter(file));
 output.write(WVdata);
 output.close();
 topBannerWV.loadUrl("file:///" + getContext().getApplicationContext().getFilesDir() + "/data.html");

I do not know why this happens, actually i do not change the data string, just put it into a file.

0
On

I am doing something like this and it works perfectly:

 webView.loadUrl("file:///android_asset/html.html");
webView.setWebViewClient(new WebViewClient() {

public void onPageFinished(WebView view, String url) {
    try {           
                webView.loadUrl("javascript:init('" + some parameter + "')");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
});

script in html file is:

<script type="text/javascript">
function init(val){
document.getElementById('content').innerHTML=val;
}
window.addEventListener('load',function(){
 console.log("Window Loader");
 init();
});
</script>