views:

476

answers:

2

I want to use stringByEvaluatingJavaScriptFromString to run a javascript which references local files (in this case css files, but potentially js files too) which are on the device (in the Documents folder I guess?)...

 NSString *theJS = [[NSString alloc]
 initWithString:@"javascript:(function()
{the_css.rel='stylesheet';
the_css.href='the_css.css';
the_css.type='text/css';
the_css.media='screen';}
)();"];

[webView stringByEvaluatingJavaScriptFromString:theJS];

How would I get this to work? It works fine if I use an external css file, like

the_css.href='http://www.website.com/the_css.css';
+1  A: 

What I've done in the past is used this code when loading the HTML

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:bundlePath];

[webView loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8 " baseURL:baseURL];

This will pass the bundle location as the base url which should cause your relative urls to work correctly. Of course you don't have to use this exact loadData method, there are various overloads. Just get the baseUrl in there and you should be good to go.

If all else fails you can use something like:

NSString *path = [[NSBundle mainBundle] pathForResource:@"file.css" ofType:nil]]

And inject that into the page with some string replacements or whatever. Bit hacky though.

Mike Weller
A: 

You should do it like this.

NSString *cssPath = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendinPathComponent:@"the_css.css"]];
NSURL *baseURL = [NSURL fileURLWithPath:cssPath];


 NSString *theJS = [[NSString alloc]
 initWithFormat:@"javascript:(function()
{the_css.rel='stylesheet';
the_css.href='%@';
the_css.type='text/css';
the_css.media='screen';}
)();",baseURL];
[cssPath release];

[webView stringByEvaluatingJavaScriptFromString:theJS];

Hope this will solve the problem.

Madhup