2009-12-12 39 views
1

我想用stringByEvaluatingJavaScriptFromString運行JavaScript它引用本地文件(在這種情況下css文件,但潛在的js文件太多),這是在設備上(Documents文件夾中我猜?)...是否有可能使用Javascript引用本地文件的stringByEvaluatingJavaScriptFromString?

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

回答

4

我在過去所做的那樣加載HTML

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

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

當使用此代碼這將通過捆綁位置作爲基地的網址,這應該會導致您的相關網址正常工作。當然,你不必使用這個確切的方法,有各種過載。在那裏獲得baseUrl,你應該很好去。

如果一切都失敗了,你可以使用類似:

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

,並注入到這一點的頁面與一些字符串替換或什麼的。雖然有點哈克。

0

你應該這樣做。

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

希望這能解決問題。

相關問題