简体   繁体   English

Android 重定向不起作用

[英]Android redirect does not work

I need to redirect in a javascript file to a given URI specified by the user.我需要在 javascript 文件中重定向到用户指定的给定 URI。

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.这适用于除 Android 设备以外的所有设备。 iOS and all modern Webbrowsers support window.location.replace(...), however Android devices don't do that. iOS 和所有现代 Web 浏览器都支持 window.location.replace(...),但 Android 设备不支持。

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.但是,如果我现在尝试使用此功能重定向,让我们说“ http://www.google.com ”,Android 设备实际上无法重定向到给定的 url。

Now is it just me being stupid here right now or is there another problem?现在只是我在这里愚蠢还是有其他问题?

Sincerly真诚的

ps the redirect function is called as an callback from an XML request sent, but that should not be an issue at all. ps 重定向函数被调用为来自发送的 XML 请求的回调,但这根本不是问题。

Android supports document.location without the href property Android 支持没有href属性的document.location

Try to use:尝试使用:

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

我认为它应该是window.location.href ,而不是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.这是一个更好的解决方案,因为它保留了原始文档的历史记录,因此您可以按照此处的说明使用后退按钮或 history.back() 导航到上一个网页

You can use match and replace in iOS but apparently not in Android.您可以在 iOS 中使用 match 和 replace,但显然不能在 Android 中使用。 In my experience this is what works for redirects in Android:根据我的经验,这适用于 Android 中的重定向:

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

您可以使用: window.location = "http://example.com";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM