Web View 会将 HTML 内容中的链接显示为带有蓝色下划线。因此,如果 HTML 中有类似
的内容<a href="...">blah blah</a>
...它作为链接清晰可见。
Web View 还允许您单击电话号码和地址(即使这些只是 HTML 中的文本,而不是链接)来启动拨号器或 map 。
如何让 Webview 显示那些带有下划线等的链接(可能是 Linkify)?在 TextView 中这很容易,因为人们可以从 TextView 获取跨度并设置它们的样式,但 Webview 没有公开任何检索该数据的方法......至少我在查看文档时没有看到。
最佳答案
下面是一些 JS 代码,可以注入(inject)这些代码来链接电话号码、电子邮件和网址:
function linkify() {
linkifyTexts(linkifyPhoneNumbers);
linkifyTexts(linkifyEmails);
linkifyTexts(linkifyWebAddresses1);
linkifyTexts(linkifyWebAddresses2);
}
function linkifyPhoneNumbers(text) {
text = text.replace(/\b\+?[0-9\-]+\*?\b/g, '<a href="tel:$&">$&</a>');
return text;
}
function linkifyEmails(text) {
text = text.replace(/(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim, '<a href="mailto:$1">$1</a>');
return text;
}
function linkifyWebAddresses1(text) {
text = text.replace(/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim, '<a href="$1" target="_blank">$1</a>');
return text;
}
function linkifyWebAddresses2(text) {
text = text.replace(/(^|[^\/])(www\.[\S]+(\b|$))/gim, '$1<a href="http://$2" target="_blank">$2</a>');
return text;
}
var linkifyTexts = function(replaceFunc)
{
var tNodes = [];
getTextNodes(document.body,false,tNodes,false);
var l = tNodes.length;
while(l--)
{
wrapNode(tNodes[l], replaceFunc);
}
}
function getTextNodes(node, includeWhitespaceNodes,textNodes,match) {
if (node.nodeType == 3) {
if (includeWhitespaceNodes || !/^\s*$/.test(node.nodeValue)) {
if(match){
if(match.test(node.nodeValue))
textNodes.push(node);
}
else {
textNodes.push(node);
}
}
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
var subnode = node.childNodes[i];
if (subnode.nodeName != "A") {
getTextNodes(subnode,includeWhitespaceNodes,textNodes,match);
}
}
}
}
function wrapNode(n, replaceFunc) {
var temp = document.createElement('div');
if(n.data)
temp.innerHTML = replaceFunc(n.data);
else{
//whatever
}
while (temp.firstChild) {
n.parentNode.insertBefore(temp.firstChild,n);
}
n.parentNode.removeChild(n);
}
关于android-webview - 使Webview的自动链接可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9744390/