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)
相关推荐
前端小超超6 小时前
如何配置capacitor 打包的ios app固定竖屏展示?
前端·ios·web app
HarderCoder6 小时前
Swift 三目运算符指南:写法、场景与避坑
swift
CocoaKier6 小时前
AI让35岁程序员再次伟大
ios·微信小程序·aigc
库奇噜啦呼6 小时前
【iOS】单例模式
ios·单例模式
2501_915909066 小时前
苹果上架App软件全流程指南:iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传与审核技巧详解
android·ios·小程序·https·uni-app·iphone·webview
2501_915921436 小时前
iOS 文件管理与能耗调试结合实战 如何查看缓存文件、优化电池消耗、分析App使用记录(uni-app开发与性能优化必备指南)
android·ios·缓存·小程序·uni-app·iphone·webview
2501_915918417 小时前
App 苹果 上架全流程解析 iOS 应用发布步骤、App Store 上架流程
android·ios·小程序·https·uni-app·iphone·webview
库奇噜啦呼7 小时前
【iOS】UIViewController生命周期
macos·ios·cocoa
2501_916007477 小时前
苹果上架全流程详解,iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传与审核要点完整指南
android·ios·小程序·https·uni-app·iphone·webview
YungFan8 小时前
iOS26适配指南之UISlider
ios·swift