使用JavaScript的UIWebView CSS注入

我正在尝试将一个本地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]; } 

谢谢,

要将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的头部

我有类似的需求。 我在捆绑包中有本地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]; } 

我建议你创建一个js文件并添加到你的项目文件中。

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"js"]; NSData *fileData = [NSData dataWithContentsOfFile:filePath]; NSString *jsString = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding]; 

你知道如何在html文件中调用js。 这是最简单,最干净的方法。