javascript - 网页是否可以检测到它是从 webview 应用程序访问的?
问题描述
假设我有一个仅包含 2 个页面的网站。
然后我创建了一个 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 的目标操作系统。
解决方案
尝试使用 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 并确定目标
推荐阅读
- spring-boot - SqlResultSetMapping 未知映射错误
- javascript - 如何在测试文件中包含 Typescript 命名空间?
- c# - 创建具有固定大小和位置的字节数组
- android - 保存和查询时 RealmList 发生变化
- apache - 访问位于 /var/www/xxxxx 和 /var/www/html/yyyyy 的 apache2 站点
- html - 为什么 css 网格区域没有像我希望的那样定位元素?
- php - MySQLi 连接到数据库作为单独 PHP 文件中的自定义函数
- google-data-studio - 创建连接器:如何在字段中放置初始/默认值
- selenium - 在 selenium 的子弹出窗口中做一些操作
- android - 仅在 JVM 上测试 AndroidX 片段(不启动模拟器/设备)