Vish
Vish

Reputation: 111

How to display image from javascript in Android web view

I want to display content from remote URL in android web view, which will be return by java script tag. In my case , java script tag return image , which should be load into web view. Here is code to render image/content from remote URL.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);

    String customHtml = "<script src='http://mytestdomain.com/test.php?w=300&h=250' type='text/javascript'></script>" ;         

    webView.loadData(customHtml, "text/html", "UTF-8");
}

URL load the content but image are broken and do not display properly. Though i can click on on the image and land into correct link.

enter image description here

I have proper permission

<uses-permission android:name="android.permission.INTERNET"/>

How can i fix it. Any help is appreciate.

Upvotes: 0

Views: 1667

Answers (2)

Vish
Vish

Reputation: 111

Broken image issue because presence of protocol-relative url (//) for the image returned by our server. These kind of URLs (//:mytestdomain.com) will force the protocol to be the same as it's parent page, and the app's web view might be missing a base scheme for the image to inherit. I placed proper protocol into url and it working fine now

Upvotes: 0

Zeero0
Zeero0

Reputation: 2790

I think the issue is with your js code. I tried this code and image is showing fine.

<html>
<body>

    <h3>A demonstration of how to access an IMG element</h3>

    <img id="myImg" src="http://via.placeholder.com/350x150" alt="The Pulpit Rock" width="304" height="228">

    <p>Click the button to get the URL of the image.</p>

    <button onclick="myFunction()">Try it</button>

    <p id="demo"></p>

    <script>
        function myFunction() {
        var x = document.getElementById("myImg").src;
        document.getElementById("demo").innerHTML = x;
        }
    </script>

</body>

Also enable DomStorage:

 webView.getSettings().setDomStorageEnabled(true);

Upvotes: 1

Related Questions