WKWebView iOS17设置UserAgent

WKWebView 设置 user-agent

参考文档

之前设置 user-agent 都是通过设置NSUserDefaults来实现的,不过升级到了iOS17之后这个方式不好用了。

老的设置方式:

Objective-c 复制代码
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

目前看通过设置 webview 里边的 customUserAgent 来实现可以的。不过设置之前最好把原始的给拿出来,把自己想要设置的给加进去。

swift 复制代码
let configuration:WKWebViewConfiguration = .init()
configuration.allowsInlineMediaPlayback = true
let webView = WKWebView(frame: self.bounds, configuration: configuration)

let oldUserAgent = webView.value(forKey: "userAgent") as? String ?? ""
webView.customUserAgent = "\(oldUserAgent) xxx"

之后自测一下:

swift 复制代码
webView.loadHTMLString("""
  <!DOCTYPE html>
  <html>
    <body>
      <div id='ua'></div>
      <script>
        setTimeout(()=>{
          let ele = document.getElementById('ua')
          ele.innerHtml = navigator.userAgent
          alert(navigator.userAgent)
        })
      </script>
    </body>
  </html>
  """, baseURL: nil)
相关推荐
徐同保11 小时前
通过ip访问nginx的服务时,被第一个server重定向了,通过设置default_server解决这个问题
ios·iphone
2501_9159184116 小时前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
2501_9160074717 小时前
没有 Mac 用户如何上架 App Store,IPA生成、证书与描述文件管理、跨平台上传
android·macos·ios·小程序·uni-app·iphone·webview
夏幻灵1 天前
HTTPS全面解析:原理、加密机制与证书体
ios·iphone
TheNextByte11 天前
如何在iPhone上恢复已删除的笔记的综合指南
笔记·ios·iphone
rose and war1 天前
python和jinja版本问题导致的访问报500
python·ios
fendoudexiaoniao_ios1 天前
iOS 列表拖拽cell排序
ios·swift
2501_915106321 天前
当 Perfdog 开始收费之后,我重新整理了一替代方案
android·ios·小程序·https·uni-app·iphone·webview
2501_915918412 天前
中小团队发布,跨平台 iOS 上架,证书、描述文件创建管理,测试分发一体化方案
android·ios·小程序·https·uni-app·iphone·webview
家里有只小肥猫2 天前
uniApp打包ios报错
ios·uni-app