WKWebView设置UserAgent

方式一
WKWebView()?.customUserAgent = newStr
方式二
WKWebView()?.setValue(newStr, forKey: "applicationNameForUserAgent")

同步获取设置
guard let tempUrl = URL(string: webViewUrl) else {
return
}
//若url无效会导致wkwebview崩溃
if UIApplication.shared.canOpenURL(tempUrl) == false {
return
}
if var userAgent = value(forKey: "userAgent") as? String {
let newStr = "(userAgent ?? "")CustomApp"
customUserAgent = newStr
}
异步获取设置
private func getUserAgent(_ isNew: Bool = false) -> String {
let tempWeb = WKWebView()
var isEnd = false
var originalUA: String = ""
tempWeb.evaluateJavaScript("navigator.userAgent", completionHandler: {
[weak self] oldAgent, _ in
let oldStr = oldAgent as? String ?? ""
let newStr = "(oldStr ?? "")CustomApp"
originalUA = isNew ? newStr : oldStr
isEnd = true
})
while(!isEnd) {
RunLoop.current.run(mode: .default, before: Date.distantFuture)
}
return originalUA
}
全局设置
evaluateJavaScript("navigator.userAgent", completionHandler: { [weak self] oldAgent, _ in
let oldStr = oldAgent as? String ?? ""
let newStr = "(oldStr)CustomApp"
UserDefaults.standard.register(defaults: ["UserAgent": newStr])
UserDefaults.standard.synchronize()
})

你可能感兴趣的:(WKWebView设置UserAgent)