假设我有一个仅包含 2 个页面的网站。
然后我创建了一个 webview react native 应用程序,它可以很简单:
App.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。
最佳答案
尝试使用 navigator.userAgent。
您可以在目标应用程序的 WebView 中设置自定义 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并确定目标
关于javascript - 网页是否有可能检测到它是从 webview 应用程序访问的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52324181/