javascript Android 重定向不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20858199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:29:05  来源:igfitidea点击:

Android redirect does not work

javascriptandroid

提问by cschaeffler

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. iOS and all modern Webbrowsers support window.location.replace(...), however Android devices don't do that.

这适用于除 Android 设备以外的所有设备。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

真诚的

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

ps 重定向函数被调用为来自发送的 XML 请求的回调,但这根本不是问题。

回答by StarsSky

Android supports document.locationwithout the hrefproperty

Android 支持document.location不带href属性

Try to use:

尝试使用:

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

For more info click here

欲了解更多信息请点击这里

回答by Ridcully

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

我认为应该是window.location.href,不是document.location.href

回答by AlvynFash

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() 导航到上一个网页

回答by Ernir Erlingsson

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

您可以在 iOS 中使用匹配和替换,但显然不能在 Android 中使用。根据我的经验,这适用于 Android 中的重定向:

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

回答by dasdasdasdasd

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

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