【问题标题】:how to determine if website is opened on iPhone/Android browser or from iPhone/Android app web view?如何确定网站是在 iPhone/Android 浏览器上打开还是从 iPhone/Android 应用程序网页视图打开?
【发布时间】:2016-02-29 08:49:53
【问题描述】:

目的是识别正在打开的网站

  • 设备浏览器
  • 或在本机应用网络视图中。
  • 寻找适用于 Android 和 iOS 的解决方案

【问题讨论】:

  • 您为什么要这样做,到目前为止您自己尝试过什么?
  • 我必须禁用网站上的某些功能,具体取决于网站是在本机应用程序还是移动浏览器中启动。

标签: javascript android ios webview uiwebview


【解决方案1】:

iPhone

在 App 中更改 UserAgent

// Modify the user-agent
NSString* suffixUA = @"AppName";
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero]; 
NSString* defaultUA = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString* finalUA = [defaultUA stringByAppendingString:suffixUA];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:finalUA, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

现在您可以通过 Javascript 进行检查:

function isIOS() {
    return /iPhone|iPad|iPod/i.test(navigator.userAgent);
}

function isIOSInApp() {
    return isIOS() && /AppName/i.test(navigator.userAgent); 
}

对于 Android:

Activity onCreate

this.webView.getSettings().setUserAgentString(
    this.webView.getSettings().getUserAgentString() 
    + " "
    + getString(R.string.user_agent_suffix)
);

Values.XML

<string name="user_agent_suffix">AppName/1.0</string>

现在您可以通过 Javascript 进行检查:

function isAndroid() {
    return /Android/i.test(navigator.userAgent);
}

function() isNativeApp {
   return isAndroid() && /AppName\/[0-9\.]+$/.test(navigator.userAgent);
}

【讨论】:

    【解决方案2】:

    您可以使用 mobileesp 提供的 mdetect.js 文件。 检查以下链接: http://www.hand-interactive.com/detect/mobileesp_demo_javascript.htm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 2011-07-04
      • 2017-04-02
      • 1970-01-01
      相关资源
      最近更新 更多