Is it possible to use stringByEvaluatingJavaScriptFromString with Javascript that references local files?

I want to use stringByEvaluatingJavaScriptFromString to run javascript that references local files (in this case, css files, but also js files) that are on the device (in the Documents folder, I think?) ...

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 do I make this work? It works fine if I use an external css file like

 the_css.href='http://www.website.com/the_css.css'; 
+1
source share
2 answers

What I did in the past uses this code when loading 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 package location as the base URL, which should result in your relative URLs working correctly. Of course, you do not need to use this exact loadData method, there are various overloads. Just take baseUrl 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 add this to the page with some line replacements or whatever. Bit is hacked though.

+4
source

You have to 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 solves the problem.

0
source

Source: https://habr.com/ru/post/893860/


All Articles