如何以编程方式修改UIWebView中的JavaScript?

时间:2010-08-16 16:59:02

标签: javascript xcode uiwebview

我需要在UIWebView中动态修改Javascript。我在本地的文档文件夹中加载了一个文件html。

我需要创建一个这样的var属性:

var attributes = {
    "feedURL": "http://www.obliviux.com/?feed=rss2", //insert NSString *RSS here
    "maxAgeToShow": "-1",  //insert NSString *maxAge here
    "numItemsToShow": "10",  //insert NSString *numItems here
    "topStories": "3"  //insert NSString *topStories here
};

用我保存的一些NSString修改它们的值..

我该怎么做?

1 个答案:

答案 0 :(得分:1)

首先,您可以从普通的NSData对象加载html数据。记住这一点,你可以从你的文件中加载一个NSString,用你的NSString替换'__feed_url__'(例如)。

UIWebView *webView = [[UIWebView alloc] initWithFrame:yourRect];
NSString *template = [[NSString alloc] initWithContentsOfFile:yourTemplateFile];
template = [template stringByReplacingOccuresOfString:@"__feed_url__" withString:yourFeedURL];
[webView loadData:[template dataUsingEncoding:NSUTF8StringEncoding] MIMEType:@"text/html" textEncodingName:@"utf8"];

除此之外,你可以考虑这个:

- (void)viewDidLoad {
    ...
    self.webView.delegate = self;
    ...
}

- (void)webViewDidFinishLoad:(UIWebView *)someWebView {
    NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"attributes['feedURL'] = '%@'", yourFeedURL]];
}

正如您所看到的,这种方式要复杂得多。