Skip to content
待添加

WebView 设置 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)