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

爱⌒轻易说出口 提交于 2019-12-05 06:47:53

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1893715/is-it-possible-to-use-stringbyevaluatingjavascriptfromstring-with-javascript-whi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!