You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android WebView中getOriginalUrl()与getUrl()的区别是什么?

Difference between getOriginalUrl() and getUrl() in Android WebView

Hey there, let's break down the key differences between these two WebView methods clearly—since I know official docs can feel a bit vague when you're trying to apply them to real code:

Core Definitions

  • getOriginalUrl(): This returns the initial URL your WebView was first told to load (via loadUrl(), loadData(), etc.). The critical thing here is this value never changes: even if the page redirects, the user navigates through multiple links, or JS modifies the address bar, this will always point back to that very first URL you started with.
  • getUrl(): This returns the current, real-time URL of the page the WebView is displaying right now. If the page redirects, the user clicks to another page, or the address bar is updated via code, this value will update to match whatever is currently loaded.

How This Applies to Your Code

Looking at your onBackPressed() implementation:

@Override 
public void onBackPressed() { 
    if (webView.getOriginalUrl().equalsIgnoreCase(URL) || webView.getOriginalUrl().equalsIgnoreCase(URL+"?id=id")) { 
        super.onBackPressed(); 
    } else if(webView.canGoBack()){
        webView.goBack(); 
    } else {
        super.onBackPressed(); 
    } 
}

You’re using getOriginalUrl() to check if you’ve circled back to the starting point of your WebView session. This makes perfect sense for your logic: you only want to exit the activity when you’ve navigated all the way back to the very first URL you loaded (including its variant with the id parameter).

If you swapped this for getUrl(), the logic would shift: it would check if the currently displayed page matches your target URLs. For example, if your initial URL redirects to another address, getUrl() would return the redirected address instead of the original one—so your condition would fail even though you’re still in the same session.

Quick Example to Drive It Home

Suppose you load https://your-app.com/start, which immediately redirects to https://your-app.com/home:

  • getOriginalUrl() returns https://your-app.com/start
  • getUrl() returns https://your-app.com/home

If the user navigates to https://your-app.com/profile then hits back to return to https://your-app.com/home:

  • getOriginalUrl() still returns https://your-app.com/start
  • getUrl() returns https://your-app.com/home

Final Note

Your current use of getOriginalUrl() is perfectly aligned with your goal of exiting only when you’re back to the session’s starting point. If you ever need to check the actual page the user is viewing right now (not just the initial load), that’s when getUrl() is the right tool for the job.

内容的提问来源于stack exchange,提问作者S.E Saint

火山引擎 最新活动