【问题标题】:Android webview "location.replace" doesn't workAndroid webview“location.replace”不起作用
【发布时间】:2012-12-29 07:24:30
【问题描述】:
我有一个 Android 网络视图,其中一个页面使用 location.replace(url) 重定向到另一个页面。
假设我有页面“A”重定向到页面“B”(使用 location.replace)。当从“B”页面按下“返回”按钮时,页面返回到“A”页面,这会将其再次重定向到“B”页面。
当我调试历史 API(history.length)时,我可以清楚地看到在页面“B”上长度增加了“1”(仅在 Android 4.X webview 上。在 iOS/Web 浏览器/Android 2.X 上保持不变),这是一个错误! (location.replace 不应更改 history.lenght!)
【问题讨论】:
标签:
javascript
android
android-webview
html5-history
【解决方案1】:
我在这个项目上与 Yaniv 合作,我们找到了问题的原因,它是在我们尝试根据 this answer 添加 mailto: 链接处理时引入的。
答案建议使用以下WebViewClient扩展类:
public class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(MailTo.isMailTo(url)){
MailTo mt = MailTo.parse(url);
// build intent and start new activity
return true;
}
else {
view.loadUrl(url);
return true;
}
}
}
问题在于明确告诉WebViewClient 加载 URL 并返回 true(意思是“我们处理了这个”)将页面添加到历史记录中。 WebView 本身非常有能力处理常规 URL,因此返回 false 并且不接触视图实例将使 WebView 加载页面并按应有的方式处理它。
所以:
public class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(MailTo.isMailTo(url)){
MailTo mt = MailTo.parse(url);
// build intent and start new activity
return true;
}
else {
return false;
}
}
}
【解决方案2】:
function locationReplace(url){
if(history.replaceState){
history.replaceState(null, document.title, url);
history.go(0);
}else{
location.replace(url);
}
}
【解决方案3】:
试试这个方法..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView mainWebView = (WebView) findViewById(R.id.webView1);
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mainWebView.loadUrl("file:///android_asset/www/A.html");
}
或从this 和this 链接获得帮助