我想用stringByEvaluatingJavaScriptFromString运行JavaScript它引用本地文件(在这种情况下css文件,但潜在的js文件太多),这是在设备上(Documents文件夹中我猜?)...

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

我将如何得到这个工作?如果我使用一个外部CSS文件,像

它工作正常
the_css.href='http://www.website.com/the_css.css';
有帮助吗?

解决方案

我已经在过去做什么加载HTML时使用此代码

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

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

这将通过束位置与基准网址这应该引起你的相对URL才能正常工作。当然,你不必使用这个确切loadData方法,有不同的过载。只是在那里得到的baseUrl,你应该是好去。

如果一切都失败了,你可以使用这样的:

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

和注入到该页面与一些字符串替换或什么的。位哈克虽然。

其他提示

您应该像这样做。

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

希望这将解决这个问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top