javascript - 是否可以将 stringByEvaluatingJavaScriptFromString 与引用本地文件的 Javascript 一起使用?

标签 javascript iphone uiwebview stringbyevaluatingjavascr

我想使用 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 传递,这应该会使您的相对 url 正常工作。当然,您不必完全使用这种 loadData 方法,有各种重载。只需将 baseUrl 放入其中,您就可以开始了。

如果一切都失败了,你可以使用类似的东西:

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

然后将其注入(inject)到带有一些字符串替换或其他内容的页面中。虽然有点老套。

关于javascript - 是否可以将 stringByEvaluatingJavaScriptFromString 与引用本地文件的 Javascript 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1893715/

相关文章:

javascript - TypeError : response. 重定向不是函数

javascript - 单击行内的按钮时,防止触发表行 onclick 事件

ios - 在 webview 中,我怎么知道输入何时应该 resignFirstResponder

ios - 在 UIWebView 中使用自定义字体

javascript - 与 Q 等效的异步瀑布

javascript - 目标 wpcf7mailsent 的特定联系人 7 表单

ios - 无法使用initWithUUIDString创建NSUUID

ios - 从其他类初始化 AppDelegate 中的对象

iphone - CAL层深度

ios - 点击手势错误,在错误的 View 中识别点击