if (navigator.userAgent.indexOf('yhdandroid') > 0) { // Android 内返回 console.log(window.history.length, 'history.length'); if (window.history && window.history.length > 1) { window.history.go(-1); } else { window.yhd.back && window.yhd.back(); } }
这段代码是实现在安卓APP内webview中返回按钮的功能,请你帮我分析下多次跳转时能否正确的返回,如果不能的话请帮我修复代码
Let's analyze the code you provided:
if (navigator.userAgent.indexOf('yhdandroid') > 0) {
// Android 内返回
console.log(window.history.length, 'history.length');
if (window.history && window.history.length > 1) {
window.history.go(-1);
} else {
window.yhd.back && window.yhd.back();
}
}
This code checks if the user agent contains 'yhdandroid', indicating it's running in an Android WebView. Then it attempts to handle the back functionality.
The current implementation has a few potential issues:
window.history.go(-1)
will only go back one step, which might not be the desired behavior.window.history.length > 1
might not always accurately represent whether there's a previous page to go back to, especially after multiple navigations.window.history.go(-1)
might fail (e.g., if there's no previous page in the WebView's history).To improve this code and ensure it works correctly with multiple navigations, we can make the following modifications:
This improved version addresses the issues in the following ways:
position
state to track the navigation depth within the WebView. This allows for more accurate back navigation.goBack
function checks the current position in the history. If we're not at the start of the WebView history, it uses window.history.go(-1)
. Otherwise, it falls back to the app's native back function (window.yhd.back
).popstate
event to handle cases where the WebView is at the start of its history, ensuring the app's native back function is called.pushstate
and replacestate
events to update the position state whenever navigation occurs within the WebView.This solution should handle multiple navigations more reliably, ensuring that the back functionality works as expected in various scenarios. It maintains the WebView's history when possible and falls back to the app's native back function when necessary.
To implement this in your app:
goBack
function when your back button is pressed.window.yhd.back
is properly implemented in your Android app to handle native back functionality.This solution should provide a more robust handling of back navigation in your Android WebView, accounting for multiple navigations and edge cases.