UIWebView CSS injection using JavaScript

冷暖自知 提交于 2019-11-28 19:39:04

To inject javascript into a web view you must explicitly write in the html.

An example of this is here where I wrote in a javascript scrollTo function:

- (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();"];}

This code writes the entire script tags and the myFunction into the head of the HTML

Jim T

I had a similar need. I have local html files in the bundle that I wanted to change css attributes programatically. Since you can not change files in the bundle, I wanted to inject my css at load time from variables in the app.

The code below demonstrates the technique, just substitute your method for getting the css, i.e. read from a file, plist, code, or 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];
}

I would suggest you to create a js file and add to your project file.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"js"];

NSData *fileData = [NSData dataWithContentsOfFile:filePath]; 

NSString *jsString = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];

and you know how to call js in html file. this is the simplest and clean way to do it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!