当前位置:网站首页>WKWebView 设置自定义UserAgent正确姿势
WKWebView 设置自定义UserAgent正确姿势
2022-07-17 00:09:00 【博BOBO】
背景
一般Web端通过UA来区分当前浏览器是在PC/Mobile/App内,所以在App内设置UA就是一个必须要做的事情。
下面介绍三种方式设置WKWebView的UserAgent(没有耐心的可以直接看最下面一种)
1. 通过UserDefaults(目前网上最常见的)
由于WKWebView有一个特性,在初始化时会获取UserDefaults中“UserAgent”这个key的值,这需要我们在真正使用的WKWebView之前要创建一个WKWebView获取他默认的UA
webView = WKWebView();
webView?.evaluateJavaScript("navigator.userAgent", completionHandler: { (obj: Any?, error: Error?) in
guard let ua = obj as? String else {
return
}
let customUA = "\(ua) Custom User Agent"
UserDefaults.standard.register(defaults: ["UserAgent": customUA])
UserDefaults.standard.synchronize()
})
2. 通过WKWebView.customUserAgent设置
* 这种方式其实和第一种方式并没有什么差别,而且还比较复杂,因为只对这一个WebView有效
let fakeWebView = WKWebView();
fakeWebView.evaluateJavaScript("navigator.userAgent", completionHandler: { (obj: Any?, error: Error?) in
guard let ua = obj as? String else {
return
}
let customUA = "\(ua) Custom User Agent"
let realWebView = WKWebView()
realWebView.customUserAgent = customUA
})
3. 通过applicationNameForUserAgent设置- 推荐
config的此属性与上一个属性不同,不是将设置的字符串完全变成你所设置的值,
它将字符串集添加到WebView的默认UserAgent并执行它。
这正好就是我们想要的,您所要做的就是设置要添加的字符串。
修改后的UserAgent,如:Mozilla/5.0 (iPhone; CPU iPhone OS 13_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Custom UserAgent
let config = WKWebViewConfiguration()
config.applicationNameForUserAgent = "Custom User Agent"
let webview = WKWebView(frame: .zero, configuration: config)
三种方式系统采用的优先级
customUserAgent > UserDefault > applicationNameForUserAgent
左侧优先级高于右侧
如果设置了customUserAgent或UserDefaults方法,则applicationNameForUserAgent将被忽略。
applicationNameForUserAgent仅添加到了webview具有的默认UserAgent中。
边栏推荐
- MapReduce environment preparation
- Uniapp development, upload pictures in the app and send them directly to OSS
- 9 无人机方阵
- [AHU2021校内赛] ez-injection
- ES6 map extract array object
- 基于CSI的通信感知一体化设计:问题、挑战和展望
- MapReduce环境准备
- How to use express and how to match and use routes
- 如何建设实时开发平台,深入释放企业实时数据价值?
- Cento7安装mysql5.5以及升级5.7
猜你喜欢

Mysql 安装(rpm包方式)

实时开发平台建设实践,深入释放实时数据价值丨04期直播回顾

MapReduce

Redis 突然变慢了?

Introduction to software vulnerability analysis (II)

Introduction to software vulnerability analysis (4)

04 BTC implementation

Dhfs read / write process

Uniapp development, upload pictures in the app and send them directly to OSS

What is the QS module?
随机推荐
What are the NFT digital collection platforms? Which platforms are worth collecting?
The platform of digital collection NFT is good
08 BTC bifurcation
axs火爆,还有哪些打金游戏(上)
MapReduce environment preparation
The use of libtomcrypt password Library
MapReduce
8 找到和最大的长度为 K 的子序列
Common asynchronous sending code writing
CheckPoint and DataNode
07 BTC mining
量子计算机带来的全新通信安全风险分析及应对建议
V-model principle and modifier
What is "digital collection"?
NFT单月万倍神话,元宇宙之门的奥秘是什么?
ChunJun支持异构数据源DDL转换与自动执行 丨DTMO 02期回顾(内含课程回放+课件)
无数次踩坑安装AWVS
大数据开源项目,一站式全自动化全生命周期运维管家ChengYing(承影)走向何方?
Classification and use of express Middleware
感通融合系统中保障公平度的时间与功率分配方法