我正在使用 phonegap/cordova 2.1.0 框架在 IOS 中制作应用程序。我想从objective-c调用驻留在index.html中的javascript函数。所以,首先我加载 index.html,然后尝试调用 javascript 函数。我的代码如下:
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"www"];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString *myFile = [path stringByAppendingPathComponent:@"index.html"];
//NSLog(@"base url= %@",myFile);
NSData *myFileData = [[NSData alloc] initWithContentsOfFile:myFile];
NSString* myFileHtml = [[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding];
[theWebView loadHTMLString:myFileHtml baseURL:baseURL];
// to call javascript function
[theWebView stringByEvaluatingJavaScriptFromString:@"onDeviceReady()"];
倒数第二行加载 index.html,最后一行调用其中的函数。但是,不知何故,上面的代码不起作用。我在语法明智的地方出错了吗?
另外,由于 index.html 之前已经加载过,那么如何在不再次加载的情况下指定函数存在的文件名(即 index.html)?谢谢。
Javascript函数如下:
function onDeviceReady(callback) {
var item = window.localStorage.getItem("key");
var message = "deviceready localStorage.getItem('key')="+item+" localStorage.length="+window.localStorage.length;
if( item == null){
item = "";
}
item = item + "value";
window.localStorage.setItem("key", item);
var value = window.localStorage.getItem("key");
if ( deviceType == 'android' && gAppControl.loadScript == false ){
loadScript('iscroll.js');
gAppControl.loadScript = true;
document.addEventListener("backButton", backPressed, false);
}
var db = window.openDatabase(dbName, "1.0", gAppConfig.dbMessage, 200000);
db.transaction(queryDB, errorCB , callback);
// return
return;
}