是否可以将stringByEvaluatingJavaScriptFromString与引用本地文件的Javascript一起使用?
我想使用stringByEvaluatingJavaScriptFromString运行一个javascript,该javascript引用本地文件(在本例中为css文件),但也可能引用设备上Documents文件夹中的js文件是否可以将stringByEvaluatingJavaScriptFromString与引用本地文件的Javascript一起使用?,javascript,iphone,uiwebview,stringbyevaluatingjavascr,Javascript,Iphone,Uiwebview,Stringbyevaluatingjavascr,我想使用stringByEvaluatingJavaScriptFromString运行一个javascript,该javascript引用本地文件(在本例中为css文件),但也可能引用设备上Documents文件夹中的js文件 NSString *theJS = [[NSString alloc] initWithString:@"javascript:(function() {the_css.rel='stylesheet'; the_css.href='the_css.css'; th
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];
这将把bundle位置作为基本url传递,这将使您的相对url正常工作。当然,您不必使用这个确切的loadData方法,有各种重载。只要把baseUrl放在那里就可以了
如果所有其他方法都失败,您可以使用以下方法:
NSString *path = [[NSBundle mainBundle] pathForResource:@"file.css" ofType:nil]]
然后用字符串替换或其他方法将其注入页面。不过有点黑。我过去所做的是在加载HTML时使用此代码
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:bundlePath];
[webView loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8 " baseURL:baseURL];
这将把bundle位置作为基本url传递,这将使您的相对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];
希望这能解决问题。你应该这样做
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];
希望这能解决问题