webview本身貌似不支持这种实现,但是我们可以通过修改链接,实现同样的效果,即在同一个webview上打开一个新窗口的链接,首先回顾一下html知识:
image.png
如果一个链接是新窗口打开,则其target值为"_blank",所以我们在onPageFinished()方法中,通过加载js,修改目标链接,使其在本webview中打开
private class MyWebview extends WebViewClient{
//这里是重点,这里修改链接
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript: var allLinks = document.getElementsByTagName('a'); if (allLinks) {var i;for (i=0; i<allLinks.length; i++) {var link = allLinks[i];var target = link.getAttribute('target'); if (target && target == '_blank') {link.setAttribute('target','_self');link.href = 'newtab:'+link.href;}}}");
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
if(url.startsWith("newtab:")){
String realUrl=url.substring(7,url.length());
Intent it = new Intent(Intent.ACTION_VIEW);
it.setData(Uri.parse(realUrl));
startActivity(it);
}else{
view.loadUrl(url);
}
return true;
}
网友评论