摘要:[PhoneGap]InAppBrowser 預設url不支援utf8的解決辦法
根據Phonegap 2.5.0的InAppBrowser文件上說明(http://docs.phonegap.com/en/2.5.0/cordova_inappbrowser_inappbrowser.md.html#InAppBrowser)
我們可以透過以下方法來在app裡面打開指定連結(透過plugin browser另開新視窗或是在原生browser上面打開)
function openBrowser(url){
var ref = window.open(url, '_blank', 'location=yes');
ref.addEventListener('loadstart', function() { alert('start: ' + event.url); });
}
上面這個方法是官方範例的使用方式,的確這樣就可以打開一個連結。但今天我們要稍微結合一下google map來讓她在goolge map上打開一個指定地址(或座標)
function openMap(address){
var url="http://maps.google.com/maps?q="+address;
openBrowser(url);
}
上面這個方法你可以帶入任何數字或英文去使用都可以在模擬器或是實機上面跑出畫面,但如果你要指定一個中文地址如"信義區信義路" 這樣就無法使用了
原來問題出在整個url沒有做encodeURI(但這邊跑實機是不會有任何錯誤,只是叫不出畫面而已),所以修改過後的版本應該為下
function openBrowser(url){
var ref = window.open(encodeURI(url), '_blank', 'location=yes');
ref.addEventListener('loadstart', function() { alert('start: ' + event.url); });
}
function openMap(address){
var url="http://maps.google.com/maps?q="+address;
openBrowser(url);
}
另外,針對InAppBrowser參數跟使用可以參考這邊(http://wiki.apache.org/cordova/InAppBrowser),以下節錄部分內容
_blank |
new in-app browser instance |
_system |
system browser |
_self |
in current browser instance |
Specification
var ref = window.open( strUrl, strWindowName[, strWindowFeatures])
strUrl
- this is a url, prefixed with a scheme for external urls or a filename for urls that exist in the local www folder
strWindowName
-
valid values are "_self", "_system", "_blank", or null. null is treated the same as "_self", any other value is treated as "_blank".
-
"_self" -> opens in the Cordova WebView if strUrl is in the white-list, else it opens in the InAppBrowser
"_system" -> always open in the system web browser
"_blank" -> always open in the InAppBrowser
-
strWindowFeatures
-
Optional parameter listing the features of the new window. The string must not contain any blank space, each feature name and value must be separated by a comma. We only support the value below:
-
location --> set to 'yes' or 'no' to turn the location bar on or off for the InAppBrowser
-
window.open returns an object that you can listen for three events on: "loadstart", "loadstop" and "exit", as well as call the "close()" function.