2012-05-16 109 views
9

我的Phonegap應用程序被允許瀏覽一些也使用Phonegap API的外部網站。目前,我有條件地包括基於你在哪個平臺上的Phonegap JavaScript(Android,iOS等)。但是,我無法分辨Phonegap應用程序與移動設備上常規瀏覽器的區別。有沒有辦法在我的Phonegap應用程序中更改用戶代理,以便爲我的服務器提供此提示?更改Phonegap用戶代理

最感興趣的是iOS解決方案。

回答

6

This answer到類似的問題也提到可用偏好當前科爾多瓦版本:

<preference name="OverrideUserAgent" value="MyCordovaApp/1.2.3" /> 

這是documented for AndroidiOS

18

如果你仍在尋找一個快速的解決方案,我這是怎麼實現的吧:

// Modify the user-agent 
NSString* suffixUA = @" my nice user-agent suffix"; 
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero]; 
NSString* defaultUA = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; 
NSString* finalUA = [defaultUA stringByAppendingString:suffixUA]; 
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:finalUA, @"UserAgent", nil]; 
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary]; 

在PhoneGap的(科爾多瓦)示例應用程序,您需要在添加這些行didFinishLaunchingWithOptions AppDelegate.m的方法

我花了一整天試圖找出這一個!我相信它可能對其他人有用。

+2

對於包含android解決方案也不錯。 –

+0

我在http://stackoverflow.com/questions/14406393/change-phonegap-cordova-user-agent-for-ajax找到了Android解決方案 – Krishna

+4

要讓@alanou解決方案正常工作,您應該添加他在return語句前面的didFinishLaunchingWithOptions方法。看來[self.window makeKeyAndVisible];必須先運行才能更改UA。在iPhone 4上使用iOS 6.1.3 – redochka

0

我不能得到這個使用科爾多瓦3.3,大概是因爲CB-2520但是,作爲一個黑客的iOS工作,我修改CDVViewController .H使userAgent財產讀寫,然後簡單地更新了viewDidLoad self.userAgent我的控制器繼承自CDVViewController

如果計時有問題,您可以強制操作CDVViewController.m中的userAgent延遲加載屬性。

這兩個都很髒。 :)

+0

[CB-2520](https://issues.apache.org/jira/browse/CB-2520)測試確定; CDVViewController現在有一個可以修改的baseUserAgent屬性 –

6

CB-2520已解決,建議允許修改用戶代理字符串。您現在可以通過設置MainViewController的baseUserAgent屬性來實現此目的。對於一個簡單的測試,你可以添加以下到didFinishLaunchingWithOptions的AppDelegate.m法,MainViewController初始化後:

self.viewController.baseUserAgent = @"My Custom User Agent";

+0

當我設置它時,這沒有任何影響......我錯過了什麼? –

3

如果您正在尋找一個功能更強大的http客戶端,它允許更改用戶代理或任何標題,請嘗試https://github.com/aporat/cordova-plugin-fetch。它包裝經過良好測試的本地網絡庫(在ios上爲AFNetworking 2,在android上爲OKHttp)。

它也遵循window.fetch,因此您可以在模擬器和設備上使用cordovaFetch,同時在fetch.js上使用瀏覽器進行測試。

只是

cordova plugin add https://github.com/aporat/cordova-plugin-fetch.git

安裝插件,包括你提出的任何請求的用戶代理頭。

cordovaFetch('/users.json', { 
    method : 'GET', 
    headers: { 
    'User-Agent': 'your user agent' 
}, 
})