1

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';

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You should do it like this.

NSString *cssPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.