Reputation: 7060
In my application , i have to change font from webPage that loaded from online.
First i store my CustomJava.js files in online hosting and i use that file to change font in my iOS app.
Here is some of my codes.
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *js = [NSString stringWithFormat:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.src = 'http://www.gustohei.com/SYjs/customJava.js';"];
js = [NSString stringWithFormat:@"%@ document.getElementsByTagName('head')[0].appendChild(script);", js];
[self.webViewOfBrowser stringByEvaluatingJavaScriptFromString:js];
UIApplication *app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
}
It's fine and change font correctly.
In my case , i want to keep that JS File in my document directory and want to use that file from document directory . i don't want to use from online.
So i wrote following code.
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *jsPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"customJava.js"];
NSString *js = [NSString stringWithFormat:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.src ='%@'",jsPath];
js = [NSString stringWithFormat:@"%@ document.getElementsByTagName('head')[0].appendChild(script);", js];
[self.webViewOfBrowser stringByEvaluatingJavaScriptFromString:js];
UIApplication *app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
}
However it's doesn't work. How to do that?
Upvotes: 0
Views: 849
Reputation: 2545
Keep the javascript file and the HTML in same folder in documents directory and Just include the javascript in the HTML you are loading over webview
<script src = "CustomJava.js" type="application/javascript"></script>
and then call the javascript function in your code like this: (for example "changeFont();" is the name of the function you want to call over webview)
NSString *javascriptFunctionCall = [NSString stringWithFormat:@"changeFont('%@');",self.fontSize];
[bookWebView stringByEvaluatingJavaScriptFromString:javascriptFunctionCall];
Upvotes: 0
Reputation: 12717
Then load the js file using following code
[[NSBundle mainBundle] pathForResource:@"script.js" ofType:nil];
UPDATE: Xcode 4.5 now creates a warning when you just add a javascript file to your project without removing it from the “Compile Sources” section:
warning: no rule to process file 'FILEPATH' of type sourcecode.javascript for architecture armv7
Upvotes: 1