xcode 如何在 OS X Yosemite 中更改 WKWebview 的用户代理?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26434269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change the WKWebview's user agent in OS X Yosemite?
提问by Jim Bak
How do you change the user agent used by WKWebview
?
您如何更改 使用的用户代理WKWebview
?
With the older WebView
, I could write the following to change the user agent:
对于较旧的WebView
,我可以编写以下内容来更改用户代理:
[myWebView setCustomUserAgent:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4)
AppleWebKit/537.77.4 (KHTML,like Gecko) Version/7.0.5 Safari/537.77.4"];
回答by PassKit
Very simple in Swift. Just place the following into your App DelegatedidFinishLaunchingWithOptions
.
在 Swift 中非常简单。只需将以下内容放入您的 App Delegate 即可didFinishLaunchingWithOptions
。
NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent" : "Custom Agent"])
If you want to append to the existing agent string then:
如果要附加到现有代理字符串,则:
let userAgent = UIWebView().stringByEvaluatingJavaScriptFromString("navigator.userAgent")! + " Custom Agent"
NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent" : userAgent])
Note: You will need to uninstall and reinstall the App to avoid appending to the existing agent string.
注意:您需要卸载并重新安装应用程序以避免附加到现有的代理字符串。
回答by micho
I don't have an answer for this. However, some pointers from my research so far:
对此我没有答案。但是,到目前为止,我的研究有一些建议:
In iOS, it's possible to set a custom user agent for a UIWebView like this:
在 iOS 中,可以像这样为 UIWebView 设置自定义用户代理:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:agent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
In OSX, there was a setCustomUserAgent
method for WebView elements that did the trick.
在 OSX 中,有setCustomUserAgent
一种用于 WebView 元素的方法可以解决问题。
However, this doesn't work for WKWebView (at least, in OSX). I couldn't find any documentation about it from Apple, either.
但是,这不适用于 WKWebView(至少在 OSX 中)。我也无法从 Apple 找到任何有关它的文档。
Hope somebody can help!
希望有人能帮忙!
回答by Rogier Spieker
I ran into the same issue, but managed to work around it using a combination of loadHTMLString
on the WKWebView
and a NSMutableURLRequest
to do the heavy lifting.
我遇到了同样的问题,但设法使用loadHTMLString
onWKWebView
和 a的组合来解决它NSMutableURLRequest
来完成繁重的工作。
My search on how to call some method on the WKWebView
itself lead me to http://trac.webkit.org/changeset/165594, which implies there is a private method _setCustomUserAgent
to do this. I'm not proficient enough in cocoa/swift to figure this one out.
我搜索如何在WKWebView
自身上调用某些方法将我带到http://trac.webkit.org/changeset/165594,这意味着有一个私有方法_setCustomUserAgent
可以做到这一点。我对可可/swift 不够精通,无法弄清楚这一点。
I ended up using the code below, as I really only need to fetch the contents of a single URL and display it, but it may be helpful in some way.
What it does is simply loading the contents of an URL into the WKWebView
as string, I suspect you may lose back/forward navigation and such, and it will only work for the initial page display, as the WKWebView
will take over clicks and asset loading.
我最终使用了下面的代码,因为我真的只需要获取单个 URL 的内容并显示它,但这在某些方面可能会有所帮助。它所做的只是将 URL 的内容加载到WKWebView
as 字符串中,我怀疑您可能会丢失后退/前进导航等,并且它仅适用于初始页面显示,因为WKWebView
它将接管点击和资产加载。
(please note, this example is written in Swift and not Objective-C)
(请注意,这个例子是用 Swift 而不是 Objective-C 编写的)
self.webView = WKWebView(frame: webViewRect, configuration: webViewConfig)
// create the request
let url = NSURL(string: "https://example.com/")
let request = NSMutableURLRequest(URL: url!)
request.setValue("YourUserAgent/1.0", forHTTPHeaderField: "User-Agent")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
let content = NSString(data: data, encoding: NSUTF8StringEncoding)
self.webView!.loadHTMLString(content!, baseURL: url)
}
回答by TomSwift
It wouldn't be ideal but you could likely implement a custom NSURLProtocol handler to intercept HTTP requests and modify them with your custom user-agent header. I don't think this would work on iOS since WKWebView makes requests out-of-process and bypasses any registered NSURLProtocols. But it might work on OS X?
这并不理想,但您可能会实现自定义 NSURLProtocol 处理程序来拦截 HTTP 请求并使用您的自定义用户代理标头修改它们。我认为这不适用于 iOS,因为 WKWebView 在进程外发出请求并绕过任何已注册的 NSURLProtocols。但它可能适用于 OS X?
回答by uchuugaka
With a user entered URL in a text field, you can completely control the NSURLRequest using an NSMutableURLRequest object, and set the header field for it.
通过用户在文本字段中输入的 URL,您可以使用 NSMutableURLRequest 对象完全控制 NSURLRequest,并为其设置标头字段。
However, with things the user actually clicks on within the web view, you're kind of not in control from obvious and clearly documented Objective-C land. I do not see any documented way beyond what WKWebView seems to push things toward, JavaScript. So, that means you can do things like posted here: Mocking a useragent in javascript?Using the script injection APIs.
但是,对于用户在 Web 视图中实际单击的内容,您无法从明显且清晰记录的 Objective-C 领域进行控制。除了 WKWebView 似乎将事情推向 JavaScript 之外,我没有看到任何有记录的方式。因此,这意味着您可以执行此处发布的操作: Mocking a useragent in javascript? 使用脚本注入 API。
This is why I do not like WKWebView. I want to like it, but I do not want to learn to do half of everything in JavaScript.
这就是我不喜欢 WKWebView 的原因。我想喜欢它,但我不想学习用 JavaScript 做一半的事情。
So, you can create a WKUserScript object to do this, and set its injection time to WKUserScriptInjectionTimeAtDocumentStart. That will enable you to handle things requested from page elements within the document, as long as the page itself is not loading other scripts that conflict.
因此,您可以创建一个 WKUserScript 对象来执行此操作,并将其注入时间设置为 WKUserScriptInjectionTimeAtDocumentStart。这将使您能够处理从文档中的页面元素请求的内容,只要页面本身没有加载其他冲突的脚本。
回答by VincentG
First Quit Safari. Then open Terminal and paste this command, and press enter:
首先退出Safari。然后打开终端并粘贴此命令,然后按 Enter:
defaults write com.apple.Safari CustomUserAgent "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/538.46 (KHTML, like Gecko) Version/7.1 Safari/537.85.7\""
默认写入 com.apple.Safari CustomUserAgent "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/538.46 (KHTML, like Gecko) Version/7.1 Safari/537.85.7\""
Open Safari and you're done.
打开Safari,你就完成了。
To undo this change, close Safari and paste this command into terminal:
要撤消此更改,请关闭 Safari 并将此命令粘贴到终端中:
defaults delete com.apple.Safari CustomUserAgent
默认删除 com.apple.Safari CustomUserAgent
Sometimes a restart may be required to get these changes to stick, not sure why, could be a cache thing.
有时可能需要重新启动才能使这些更改保持不变,不知道为什么,可能是缓存问题。