首页 > 解决方案 > 网页是否可以检测到它是从 webview 应用程序访问的?

问题描述

假设我有一个仅包含 2 个页面的网站。

  1. http://example.com
  2. http://example.com/webview.html

然后我创建了一个 webview react native 应用程序,它可以很简单:

应用程序.js

import React, { Component } from 'react';
import { WebView } from 'react-native';

export default class MyWeb extends Component {
  render() {
    return (
      <WebView
        source={{uri: 'http://example.com/webview.html'}}
        style={{marginTop: 20}}
      />
    );
  }
}

现在我的问题是:网页是否有可能检测到它是从 webview 应用程序访问的?

假设我在 webview.html 文件中有一个条件,例如:

if ( webview ) {
  return 'webview';
}
else {
  return 'normal browser'
}

也许像插入javascript,也许是从webview到网页的变量?然后我可以使用该变量来检查它的存在,如果它存在则它是 webview,否则它不是。

我知道 javascript 可以检测使用的浏览器、屏幕分辨率、操作系统等。那么这可能吗?

该应用程序具有 Android 和 iOS 的目标操作系统。

标签: javascriptandroidiosreact-nativewebview

解决方案


尝试使用 navigator.userAgent。

您可以在目标应用程序的 web 视图中设置自定义 UserAgent。

对于 iOS:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newUserAgent = [userAgent stringByAppendingString:@" Your Custom Key"];//your custom key
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}

对于安卓:

WebSettings settings = webview.getSettings();

String ua = webview.getSettings().getUserAgentString();  
webview.getSettings().setUserAgentString(ua+"; Your Custom Key");

在 h5 中,您可以获取 ua 并确定目标


推荐阅读