[英]UIWebView CSS injection using JavaScript
我正在嘗試將一個本地css文件注入一個UIWebView,完成加載網站,如谷歌等。
我正在嘗試使用JavaScript但沒有成功。
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *cssPath = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"styles.css"]];
NSURL *baseURL = [NSURL fileURLWithPath:cssPath];
NSString *js = [NSString stringWithFormat:@"var fileref = document.createElement('link');
fileref.setAttribute('rel', 'stylesheet');
fileref.setAttribute('type', 'text/css');
fileref.setAttribute('href', %@);", baseURL];
[webView stringByEvaluatingJavaScriptFromString:js];
}
謝謝,
我有類似的需求。 我在捆綁包中有本地html文件,我想以編程方式更改css屬性。 由於你無法更改bundle中的文件,我想在加載時從應用程序中的變量注入我的css。
下面的代碼演示了該技術,只需用您的方法替換獲取css,即從文件,plist,代碼或db中讀取。
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString* css = @"\"@font-face { font-family: 'Chalkboard'; src: local('ChalkboardSE-Regular'); } body { background-color: #F0F0FC; color: #572B00; font-family: Chalkboard;} a { color: #A00; text-decoration: none;}\"";
NSString* js = [NSString stringWithFormat:
@"var styleNode = document.createElement('style');\n"
"styleNode.type = \"text/css\";\n"
"var styleText = document.createTextNode('%@');\n"
"styleNode.appendChild(styleText);\n"
"document.getElementsByTagName('head')[0].appendChild(styleNode);\n",css];
NSLog(@"js:\n%@",js);
[self.webView stringByEvaluatingJavaScriptFromString:js];
}
要將javascript注入Web視圖,您必須在html中明確寫入。
這里的一個例子是我在javascript scrollTo函數中寫的地方:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function myFunction() { "
"window.scrollTo(100,100)"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
[webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];}
此代碼將整個腳本標記和myFunction寫入HTML的頭部
我建議你創建一個js文件並添加到你的項目文件中。
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"js"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSString *jsString = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
你知道如何在html文件中調用js。 這是最簡單,最干凈的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.