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]];
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...
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.
Related
I am using .js file to validate .html file in my application,the .js&.html files added in my project,but the .js file not stored in package contents,only contains the .html file,I am using ios simulator 5.0,
my validation source is..
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *urlAddress = [[NSBundle mainBundle] pathForResource:#"index"
ofType:#"html"]; //you can also use PDF files
NSLog(#"%#",urlAddress);
NSURL *url = [NSURL fileURLWithPath:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[web loadRequest:requestObj];
web.backgroundColor=[UIColor redColor];
}
- (IBAction)markHighlightedString:(id)sender {
// The JS File
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"HighlightedString" ofType:#"js" inDirectory:#""];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
[web stringByEvaluatingJavaScriptFromString:jsString];
// The JS Function
NSString *startSearch = [NSString stringWithFormat:#"stylizeHighlightedString()"];
[web stringByEvaluatingJavaScriptFromString:startSearch];
}
- (IBAction)getHighlightedString:(id)sender {
// The JS File
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"HighlightedString" ofType:#"js" inDirectory:#""];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
[web stringByEvaluatingJavaScriptFromString:jsString];
// The JS Function
NSString *startSearch = [NSString stringWithFormat:#"getHighlightedString()"];
[web stringByEvaluatingJavaScriptFromString:startSearch];
NSString *selectedText = [NSString stringWithFormat:#"selectedText"];
NSString * highlightedString = [web stringByEvaluatingJavaScriptFromString:selectedText];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Highlighted String"
message:highlightedString
delegate:nil
cancelButtonTitle:#"Oh Yeah"
otherButtonTitles:nil];
[alert show];
//[alert release]; // not required anymore because of ARC
}
- (IBAction)removeAllHighlights
{
// calls the javascript function to remove html highlights
[web stringByEvaluatingJavaScriptFromString:#"uiWebview_RemoveAllHighlights()"];
}
I am getting null value in NSLog(#"%#",filePath);//HighlightedString.js
I'm not totally sure, but could it be that you haven't copied that file to the target's output? Or, that you're using an out-dated version of the app that's being run? An easy fix might be just to do a Clean and then a Build and Run. Also, the file might be not be set to go into the target. You can change that by going to Target > Build Phases > Copy Bundle Resources. This will bring up an area where you can add that file.
Following that, I usually do a Clean and then a Build just to make sure I'm getting a new version of the application.
Addition
Also, you might try setting the inDirectory: part of the method where you're setting filePath to nil instead of specifying an empty string. Or, you could just get rid of that altogether and [[NSBundle mainBundle] pathForResource:#"HighlightedString" ofType:#"js"]
You can try these two options
1- click on js file in the project navigator then in the properties you needd to check a check box to include it in the build. This image I made before check step one and four only.
2- just write the JavaScript into the HTML file and put it inside function and call this function and stop loading it as text. So stringByEval.... Will take the JavaScript function only.
I am trying to load a UIWebView with local HTML/CSS that is build to look like a nutrition label. The problem is, the data for the food lies inside of my iPhone app. Do I have to put all of my HTML into one enormous NSString object and concatenate my data into it, or is there a way to load the HTML from a local .html file, but somehow "inject" the data that is stored within Objective-C into it?
If the data to be injected is "safe", you could construct your "enormous NSString object" as a format string, sprinkled with %# markers, and use stringWithFormat: to perform the injection in a single move. This is how I construct the pages in the TidBITS News app, using pieces that all come from RSS. It's really quite painless.
You can load basic html using NSData's method dataWithContentsOfFile and then use javascript to modify html in the way you need.
Code would look something like this (using this example):
NSString *path = [[NSBundle mainBundle] pathForResource:#"food" ofType:#"html"];
NSData *data = [NSData dataWithContentsOfFile:path];
if (data) {
[webView loadData:data MIMEType:#"text/html" textEncodingName:#"UTF-8"];
}
[webView stringByEvaluatingJavaScriptFromString:#"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function myFunction() { "
"var field = document.getElementById('field_3');"
"field.value='Calling function - OK';"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
[webView stringByEvaluatingJavaScriptFromString:#"myFunction();"];
I would do a hybrid of both- have an HTML file in the app that you load, then replace certain strings in that before giving it to the UIWebView. So for example, you could have a file like this
<html>
<head>
<title><!--foodName--></title>
</head>
<body>
<h1><!--foodName--></h1>
<p>Calories / 100g: <!--foodCalories--></p>
</body>
</html>
You'd load that into Cocoa, then replace your special placeholder comments with the actual values you want.
NSDictionary *substitutions = [NSDictionary dictionaryWithObjectsAndKeys:
#"Carrots", #"foodName",
[NSNumber numberWithInt:20], #"foodCalories",
// add more as needed
nil];
NSMutableString *html = [NSMutableString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"foodCard" ofType:#"html"]
encoding:NSUTF8StringEncoding
error:nil];
for(NSString *substitutionKey in substitutions)
{
NSString *substitution = [[substitution objectForKey:substitutionKey] description];
NSString *searchTerm = [NSString stringWithFormat:#"<!--%#-->", substitutionKey];
[html replaceOccurrencesOfString:searchTerm withString:substitution options:0 range:NSMakeRange(0, [html length])];
}
[webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
Since iOS 2 you can use - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script within a UIWebView subclass to execute JS scripts in your webview. This is the best way to inject data from the "Objective-C part" of your application.
Cf: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString:
I new to iOS programming and tried to figure out what loadHTMLString:baseURL: really does, but I can't find a satisfying explanation. The site of Apple just says:
Sets the main page content and base URL.
Can someone please explain this in a more detailed way to me?
I am pretty certain that the baseURL is used just like in regular web pages to properly load ressources that are referenced using relative links. Now the question is, how to set that base URL to a particular folder in the app directory.
This is how mainly content is loaded in a webView. either from a local html file or through a url.
//this is to load local html file. Read the file & give the file contents to webview.
[webView loadHTMLString:someHTMLstring baseURL:[NSURL URLWithString:#""]];
//if webview loads content through a url then
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]]]
- (void) loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
is used to load local HTML file, parameter string means content of html file, if your HTML file contains some href tag with relative path, you should set the parameter baseUrl with the base address of the HTML file, or set it nil.
NSString *cachePath = [self cachePath];
NSString *indexHTMLPath = [NSString stringWithFormat:#"%#/index.html", cachePath];
if ([self fileIsExsit:indexHTMLPath]) {
NSString *htmlCont = [NSString stringWithContentsOfFile:indexHTMLPath
encoding:NSUTF8StringEncoding
error:nil];
NSURL *baseURL = [NSURL fileURLWithPath:cachePath];
[self.webView loadHTMLString:htmlCont baseURL:baseURL];
}
- (NSString *)cachePath
{
NSArray* cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
return [cachePath[0] stringByAppendingPathComponent:#"movie"];
}
I have web page having 1000's of images and values. Whenever I load the page to UIWebView it gets loaded with values but as there are so many images it takes time to download.
So is there any way, I can download the page from web but images from local.
Any help is really appreciated.
Thank you,
Ankita
If you have your HTML from webserver and images at local
yourBaseURL = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[webView loadHTMLString:#"YourHTML" baseURL:yourBaseURL]
and your HTML contains name of local image stored like
Image Tag like --> imgage src='fig1.jpg width=150 height=150 align="left"
Than this should work.
Not exactly as you required though this way you can load local images in webView.
Basically:
Download HTML from server.
NSURL *URL = [[NSURL alloc] initWithString:#"http://www.example.com/page.php"];
NSError *error = nil;
NSStringEncoding encoding;
NSString *theSource = [[NSString alloc] initWithContentsOfURL:URL usedEncoding:&encoding error:&error];
Replace the file references to load images locally.
Note the double slashes, this seems important.
// Replace:
<img src="File.png">
// By something like:
<img src="file://Path//To//Resources//File.png">
Detailed information how to do this (check post by Joe D'Andrea):
Link to resources inside WebView - iPhone
Finally make the UIWebView load the HTML:
[webView loadHTMLString:htmlString baseURL:baseURL];
Now it should load the 'fresh' HTML from the server with local images.
This works quite well for me.
NSURL *myBaseURL = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSString *myString = [[managedObject valueForKey:#"long_presentation"] stringByReplacingOccurrencesOfString:#"/FooFolder/BarFolder" withString:[NSString stringWithFormat:#"%#/FooFolder/BarFolder", [[NSBundle mainBundle] bundlePath] ] ];
[attractionWebView loadHTMLString:myString baseURL:myBaseURL];
I had to include a replacement for the image source
img src="FooFolder/BarFolder/my_image.jpg" ...
to get the right path.
I wanted an entire page of text(multiple lines) in my settings similar to the one on iphone:
settings->general settings->About->Legal
I have not been able to do so. I tried entering title in PSGroupSpecifier, it gives me multiple lines but with a gray background. i wanted a white background.
Any help would be highly appreciated.
Thanks in advance
Use a UIWebView and store your page as a HTML file in your resources.
// Create the UIWebView
UIWebView *webView = [[[UIWebView alloc] initWithFrame:self.view.frame] autorelease];
// Add the UIWebView to our view
[self.view addSubview:webView];
// Load the HTML document from resources
NSString *pagePath = [[NSBundle mainBundle] pathForResource:#"legal" ofType:#"html"];
NSURL *pageURL = [NSURL fileURLWithPath:pagePath];
NSURLRequest *pageReq = [NSURLRequest requestWithURL:pageURL];
[webView loadRequest:pageReq];