Antonio Giarrusso
Antonio Giarrusso

Reputation: 820

How to modify JavaScript in a UIWebView programmatically?

I need to modify dynamically a Javascript inside my UIWebView. I load a file html locally, inside the Documents folder of my app.

I need to create a var attributes like this:

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
};

And modify their value with some NSString I have saved..

How can i do this?

Upvotes: 1

Views: 1091

Answers (1)

cutsoy
cutsoy

Reputation: 10251

First of all, you can load your html-data from a plain NSData-object. Keeping that in mind, you can load a NSString from your file, replacing '__feed_url__' (for example) with your NSString.

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"];

Besides that, you could consider this:

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

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

As you can see, this way is far more complicated.

Upvotes: 1

Related Questions