Inject Javascript functions into a UIWebView

When working with UIWebViews it is often needed to change the appearance of the pages when it is already visible to the user. What if you want give him the possibility to change font or font size?

The answer is the UIWebView method

stringByEvaluatingJavaScriptFromString

And here are some easy examples:

[objc]
-(void)changeFontNameTo:(NSString *)fontName{
NSString *jsFixedString = @”document.getElementsByTagName(‘body’)[0].style”;
NSString *jsString = [[NSString alloc] initWithFormat:@”%@.fontFamily=’%@'”,jsFixedString,fontName];
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
}

-(void)changeFontSizeTo:(NSInteger)fontSize{
//fontSize is in percentage
NSString *jsString = [[NSString alloc] initWithFormat:@”document.getElementsByTagName(‘body’)[0].style.fontSize= ‘%d%%'”, fontSize];
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
}

-(void)changeLineSpacingTo:(NSInteger)lineSpacing{
NSString *jsFixedString = @”document.getElementsByTagName(‘body’)[0].style”;
NSString *jsString = [[NSString alloc] initWithFormat:@”%@.lineHeight=’%d%%'”,jsFixedString,lineSpacing];
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
}

-(void)changeMarginTo:(NSInteger)margin{
NSString *jsFixedString = @”document.getElementsByTagName(‘body’)[0].style”;
NSString *jsString = [[NSString alloc] initWithFormat:@”%@.marginLeft=’%d%%’;%@.marginRight=’%d%%'”,
jsFixedString,margin,jsFixedString,margin];
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
}
[/objc]

For full explanation read also: How To Inject JavaScript Functions Into a UIWebView by Nick Dalton.