Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly embed tweet inside Android WebView?

I have an issue with a WebView containing some HTML data (I don't load an URL but custom content in HTML). I use:

mWebView.loadData(mContent, "text/html; charset=utf-8", "utf-8");

Inside this HTML code (mContent), I have sometimes a Twitter blockquote embed code, like this one for example:

<blockquote class="twitter-tweet"><p>"Will Remote Play on the PS Vita be available for <a    style="color:#ff8600;" href="https://twitter.com/search?q=%23D3&src=hash">#D3</a> Ultimate Edition on <a style="color:#ff8600;" href="https://twitter.com/search?q=%23PS4&src=hash">#PS4</a>?" The answer is yes, and it's awesome! <a style="color:#ff8600;" href="http://t.co/Rg059nXZMF">pic.twitter.com/Rg059nXZMF</a></p> Diablo (@Diablo) <a style="color:#ff8600;" href="https://twitter.com/Diablo/statuses/400073137590530048">November 12, 2013</a></blockquote>

So what's the problem? Well, my WebView only show the text of the tweet without style or image. (This code works perfectly on my iOS app.)

I have setJavaScriptEnabled(true) on my WebView, tried several things with WebChromeClients and loadDataWithBaseURL, but I didn't manage to get the embedded tweet showing nicely on my WebView.

Do anyone have any idea how can I do it?

like image 971
PTouch Avatar asked Mar 21 '23 16:03

PTouch


1 Answers

There are a couple of ways I can think of to solve this issue:

You could replace your call to loadData with:

loadDataWithBaseURL("https://twitter.com", mContent, "text/html", "UTF-8", null);

Or, you could make sure that the html string (mContent) has the following in its head:

<script type="text/javascript" src="https://platform.twitter.com/widgets.js"></script>

If you don't have control of the incoming HTML, you could try using Jsoup to amend the content yourself.

Document doc = Jsoup.parse(mContent);
doc.head().appendElement("script").attr("type", "text/javascript").attr("src", "https://platform.twitter.com/widgets.js");

// This is the html that includes the appropriate reference to Twitter's widgets.js script
String newHtml = doc.toString();
like image 190
HBG Avatar answered Apr 05 '23 23:04

HBG