是否可以将stringByEvaluatingJavaScriptFromString与引用本地文件的Javascript一起使用? [英] Is it possible to use stringByEvaluatingJavaScriptFromString with Javascript which references local files?

查看:106
本文介绍了是否可以将stringByEvaluatingJavaScriptFromString与引用本地文件的Javascript一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用stringByEvaluatingJavaScriptFromString来运行一个javascript,它引用设备上的本地文件(在本例中为css文件,但也可能是js文件)(我猜在Documents文件夹中?)...

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

我如何才能使用它?如果我使用外部css文件,它可以正常工作,例如

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


推荐答案

我过去所做的就是用这个加载HTML时的代码

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

这会将捆绑位置作为基本网址传递,这会导致您的相对网址正常工作。当然你不必使用这个确切的 loadData 方法,有各种重载。只需在那里获得 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]]

并将其注入页面并添加一些字符串或其他内容。但是有点hacky。

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

这篇关于是否可以将stringByEvaluatingJavaScriptFromString与引用本地文件的Javascript一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆