Failed to render Facebook comments on Android WebView via local HTML
Asked Answered
M

1

8

I have a simple activity that create a WebView to load Facebook Comments, e.g.

  protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView myWebView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        // myWebView.loadUrl("http://192.168.0.2/facebook.html"); // See 1st image
        myWebView.loadUrl("file:///android_asset/facebook.html"); // See 2nd image
    }

Only the call to remote html file work, but the local one does not work. See the following images:

via Remote file

via remote file

via Local file

via local file

And the content of facebook.html

![<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)\[0\];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "http://connect.facebook.net/en_US/all.js#xfbml=1&appId=xxx";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<div class="fb-comments" data-href="http://example.com" data-width="470" data-num-posts="10"></div>

  </body>
</html>
Milka answered 23/3, 2013 at 6:51 Comment(0)
O
7

You need to specify a base URL.

myWebView.loadDataWithBaseURL("http://www.example.com", "YOUR_HTML", "text/html", null, null)

To fully replace the line above:

BufferedReader reader = new BufferedReader(new FileReader("file:///android_asset/facebook.html"));
String line;
String html = "";
while((line = reader.readLine()) != null) {
    html += line;
}
reader.close();
myWebView.loadDataWithBaseURL("http://www.example.com", html, "text/html", null, null)
Openeyed answered 26/3, 2013 at 7:19 Comment(3)
There's a javascript console error that's logged, and I noticed the domain parameter on the request was empty.Openeyed
Ic, but what is the JavaScript console you mentioned?Milka
See developer.android.com/guide/webapps/debugging.html#WebView for catching js console logs in a WebView. It's still working for me with the same test app I wrote the other day, is there anything you've changed?Openeyed

© 2022 - 2024 — McMap. All rights reserved.