如何在 Android WebView 中正确嵌入推文? [英] How to correctly embed tweet inside Android WebView?

查看:25
本文介绍了如何在 Android WebView 中正确嵌入推文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些 HTML 数据的 WebView 的问题(我不加载 URL,而是加载 HTML 中的自定义内容).我使用:

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");

在这个 HTML 代码 (mContent) 中,我有时会有一个 Twitter 块引用嵌入代码,例如这个:

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>

有什么问题吗?好吧,我的 WebView 只显示没有样式或图像的推文文本.(此代码在我的 iOS 应用上运行良好.)

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.)

我在我的 WebView 上设置了 setJavaScriptEnabled(true),尝试了一些 WebChromeClients 和 loadDataWithBaseURL,但我没有设法让嵌入的推文在我的 WebView 上很好地显示.

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?

推荐答案

我可以想到几种方法来解决这个问题:

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

您可以将您对 loadData 的调用替换为:

You could replace your call to loadData with:

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

或者,您可以确保 html 字符串 (mContent) 的头部包含以下内容:

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>

如果您无法控制传入的 HTML,您可以尝试使用 Jsoup 自行修改内容.

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();

这篇关于如何在 Android WebView 中正确嵌入推文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆