简体   繁体   English

如何在OS X Yosemite中更改WKWebview的用户代理?

[英]How do I change the WKWebview's user agent in OS X Yosemite?

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"];

Very simple in Swift. 在Swift中非常简单。 Just place the following into your App Delegate didFinishLaunchingWithOptions . 只需将以下内容放入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. 注意:您需要卸载并重新安装应用程序,以避免附加到现有代理字符串。

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中,有一个用于WebView元素的setCustomUserAgent方法。

However, this doesn't work for WKWebView (at least, in OSX). 但是,这对WKWebView不起作用(至少在OSX中)。 I couldn't find any documentation about it from Apple, either. 我也找不到Apple的任何文档。

Hope somebody can help! 希望有人可以帮忙!

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上的WKWebViewNSMutableURLRequest的组合来解决这个问题。

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. 我对如何在WKWebView上调用某个方法的WKWebView引导我访问http://trac.webkit.org/changeset/165594 ,这意味着有一个私有方法_setCustomUserAgent来执行此操作。 I'm not proficient enough in cocoa/swift to figure this one out. 我对cocoa / 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. 我最终使用下面的代码,因为我真的只需要获取单个URL的内容并显示它,但它可能在某种程度上有所帮助。 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的内容作为字符串加载到WKWebView中,我怀疑你可能会丢失后退/前进导航等等,它只适用于初始页面显示,因为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)
}

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. 这可能不太理想,但您可能会实现自定义NSURLProtocol处理程序来拦截HTTP请求并使用您的自定义用户代理标头修改它们。 I don't think this would work on iOS since WKWebView makes requests out-of-process and bypasses any registered NSURLProtocols. 我认为这不适用于iOS,因为WKWebView会在进程外发出请求并绕过任何已注册的NSURLProtocols。 But it might work on OS X? 但它可能适用于OS X?

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. 但是,根据用户在Web视图中实际点击的内容,您无法控制明显且清晰记录的Objective-C域。 I do not see any documented way beyond what WKWebView seems to push things toward, JavaScript. 除了WKWebView似乎推动的事情,我没有看到任何记录的方式,JavaScript。 So, that means you can do things like posted here: Mocking a useragent in javascript? 所以,这意味着你可以做点这里发布的事情: 在javascript中模拟一个useragent? Using the script injection APIs. 使用脚本注入API。

This is why I do not like WKWebView. 这就是我不喜欢WKWebView的原因。 I want to like it, but I do not want to learn to do half of everything in JavaScript. 我想要它,但我不想学习用JavaScript做一半的事情。

So, you can create a WKUserScript object to do this, and set its injection time to WKUserScriptInjectionTimeAtDocumentStart. 因此,您可以创建一个WKUserScript对象来执行此操作,并将其注入时间设置为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. 这将使您能够处理文档中页面元素所请求的内容,只要页面本身不加载其他冲突的脚本。

First Quit Safari. 首先退出Safari。 Then open Terminal and paste this command, and press enter: 然后打开终端并粘贴此命令,然后按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,类似Gecko)版本/ 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. 有时可能需要重新启动才能使这些更改坚持,不确定原因,可能是缓存的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在OS X 10.10(Yosemite Beta)中,如何使用iOS 6.1模拟器进行测试? - In OS X 10.10 (Yosemite Beta), How do I Test Using iOS 6.1 Simulator? 如何在WKWebView中关闭OS X的Smart Quotes替换? - How can I turn off OS X's Smart Quotes replacement in my WKWebView? 如何修复 Xcode 6、Mac OS X Yosemite 或 Mavericks 中的“代码对象在子组件中根本没有签名:”? - How do you fix "code object is not signed at all In subcomponent:" in Xcode 6, Mac OS X Yosemite or Mavericks? 在Mac OS X 10.10 Yosemite上出现错误消息“更改项目的最低部署目标或升级My Mac的OS X版本。”? - Error message on mac os x 10.10 Yosemite “Change your project’s minimum deployment target or upgrade My Mac’s version of OS X.”? 我可以在没有CLDT的OS X Yosemite上安装/使用git吗? - Can I install/use git on OS X Yosemite without CLDT? 我可以在OS X 10.10 Yosemite上安装XCode 7.3吗? - Can I install XCode 7.3 on OS X 10.10 Yosemite? 在OS X Yosemite上安装xcode 4 - Install xcode 4 on OS X Yosemite 如何更改用户代理? - How to change User Agent? 如何在OS X Yosemite 10.10.3上安装Xcode 7 beta? - How to install Xcode 7 beta on OS X Yosemite 10.10.3? 我想在OS X Yosemite上运行xcode项目,就像它在OS X El Capitan上运行一样 - I want to run xcode project on OS X Yosemite as if it was run on OS X El Capitan
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM