1. 一般調用
將本地數據,封裝,直接作爲JS的返回值。如:獲取軟件的APPCode
//獲取APPCode
NSArray *_plist_paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *_plist_paths_path=[_plist_paths objectAtIndex:0];
NSArray *_plist_array= [_plist_paths_path componentsSeparatedByString:@"/"];
NSString *_appcode=[[NSString alloc]init];
for (NSString *item in _plist_array) {
if ([item length]==36) {
_appcode=item;
break;
}
}
NSLog(@"current appcode:%@",_appcode);//注入到js中
NSMutableString *_getApkCode=[[NSMutableString alloc]init];
[_getApkCode appendFormat:@" function _getApkCode(){"];
[_getApkCode appendFormat:@"return '%@';",_appcode];
[_getApkCode appendString:@" }"];
[self.webView stringByEvaluatingJavaScriptFromString:_getApkCode];
[_getApkCode release];
2.需要跟平臺進行交互調用
思路:
1.製造含有一定含義的請求如:(location.href="download");
2.在方法:-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType中,攔截:
//testMall:http://192.168.1.20:8083本地測試頁面地址
NSString *pre_download=[NSString stringWithFormat:@"%@downLoad",testMall];
if([url hasPrefix:pre_download])
{//下載代碼。。。。
}
3. 注意事項
a.存在Iframe嵌套的頁面,js注入
頁面注入JS是注入到,瀏覽器的html中,對於內部嵌套iframe框架的頁面,則無法調用到js。此時相當於調用父頁面的JS。
可以通過parent+方法名,來調用你注入的JS。parent.parent的使用個數,可以是多個,不影響js的執行,如果少用parent,可能會導致,調不到你注入的JS
b.存在交互的處理方法。推薦使用方法,iphone只負責提供js接口,不調用html內部或其他的js接口
示例:
html
function addDownload()
{
url='www.XXX.XXX.zip';
download(url);//調用iphone提供的js接口
addDownloadTask_ret();//獲取iphone下載接口執行的下載結果,此處調的是本地的一個延遲方法
}
//獲取iphone下載接口執行的下載結果
function addDownloadTask_ret()
{var obj=getDownloadTaskResult();//此處爲iphone提供的接口,負責返回當前下載執行情況的結果
if(''!=obj||undefined!=obj)
{//調用本地的一些後續處理方法。
}
else
{
setTimeout("addDownloadTask_ret2();",1000);
}}