admin管理员组

文章数量:1187852

I need to redirect in a javascript file to a given URI specified by the user.

So a quick example how I do this:

function redirect(uri) {
  if(navigator.userAgent.match(/Android/i)) {
    document.location.href=uri;      
  }
  window.location.replace(uri);
}

This works fine for everything except Android devices. iOS and all modern Webbrowsers support window.location.replace(...), however Android devices don't do that.

But if I now try to redirect using this function, lets say to "" the android devices fail to actually redirect to the given url.

Now is it just me being stupid here right now or is there another problem?

Sincerly

p.s. the redirect function is called as an callback from an XML request sent, but that should not be an issue at all.

I need to redirect in a javascript file to a given URI specified by the user.

So a quick example how I do this:

function redirect(uri) {
  if(navigator.userAgent.match(/Android/i)) {
    document.location.href=uri;      
  }
  window.location.replace(uri);
}

This works fine for everything except Android devices. iOS and all modern Webbrowsers support window.location.replace(...), however Android devices don't do that.

But if I now try to redirect using this function, lets say to "http://www.google.com" the android devices fail to actually redirect to the given url.

Now is it just me being stupid here right now or is there another problem?

Sincerly

p.s. the redirect function is called as an callback from an XML request sent, but that should not be an issue at all.

Share Improve this question asked Dec 31, 2013 at 13:32 cschaefflercschaeffler 4533 gold badges6 silver badges17 bronze badges 2
  • Android 4.0 supports it :> – Andy Commented Jan 2, 2014 at 18:16
  • webview code please? – Darpan Commented Nov 5, 2014 at 13:35
Add a comment  | 

5 Answers 5

Reset to default 22 +50

Android supports document.location without the href property

Try to use:

function redirect(uri) {
  if(navigator.userAgent.match(/Android/i)) 
    document.location=uri;      
  else
    window.location.replace(uri);
}

I think it should be window.location.href, not document.location.href.

I would suggest :

location.assign('someUrl');

It's a better solution as it keeps history of the original document, so you can navigate to the previous webpage using back-button or history.back() as explained here.

You can use match and replace in iOS but apparently not in Android. In my experience this is what works for redirects in Android:

<script type="text/javascript"> // <![CDATA[
    if ( (navigator.userAgent.indexOf('Android') != -1) ) {
        document.location = "http://www.your URL/your HTML file.html";
    } // ]]>
</script>

You can just use: window.location = "http://example.com";

本文标签: javascriptAndroid redirect does not workStack Overflow