Rani
Rani

Reputation: 3453

JavaScript method is not getting called on web view in iOS

I have an HTML file and JS file in my app. When the web view is loaded I am loading my html file which contains the reference to JavaScript file. I have added the JavaScript file in to my bundle resource for compile sources and in the web view did finish load I am calling a JavaScript function which increases the font size of HTML content but the JavaScript method is not getting called.

This is my code:

NSString *readerstring = @"document.getElementById('reader')";
      [webView stringByEvaluatingJavaScriptFromString:[[NSString alloc]initWithFormat:@"adjustFontSize('%@'.contentDocument, '4.0')",readerstring]];

Upvotes: 0

Views: 1219

Answers (2)

ajithmn89
ajithmn89

Reputation: 249

Call the JS function after web view finished its loading.

And if you are using any of jQuery functions don forget to add jquery.js and evaluate it.

    -(void)webViewDidFinishLoad:(UIWebView *)webView{

    NSMutableString  *jsStr  =[[NSMutableString alloc] initWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"jquery.min" ofType:@"js"]] encoding:NSUTF8StringEncoding];
    [WebView stringByEvaluatingJavaScriptFromString:jsStr];
jsStr  =[[NSMutableString alloc] initWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"yourown" ofType:@"js"]] encoding:NSUTF8StringEncoding];
    [WebView stringByEvaluatingJavaScriptFromString:jsStr];
//evalute your js file before calling its function 
[WebView stringByEvaluatingJavaScriptFromString:@"myFunctionToChangethefontSize();"];

 //change font size directly
    [WebView stringByEvaluatingJavaScriptFromString:@"$('#divContent').css('font-size', '18px');"];

    }

Important:

Check whether the JS file in compile resource bundle then you have to remove it from there and add it in copy Bundle Resource.

Upvotes: 0

Venk
Venk

Reputation: 5955

You can change the font size of UIWebView like this,

int fontSize = 20;
NSString *String = [[NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'", fontSize];
[myWebView stringByEvaluatingJavaScriptFromString:jsString];

or

[myWebView stringByEvaluatingJavaScriptFromString: @"document.body.style.fontSize = '8px'"];

Hope it will helps you...

Upvotes: 1

Related Questions