Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

iphone - UIWebView CSS injection using JavaScript

I'm trying to inject a local css file into an UIWebView that finished loading website such as google etc.

I'm trying with JavaScript but with no success.


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

Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');
"
                 "styleNode.type = "text/css";
"
                 "var styleText = document.createTextNode('%@');
"
                 "styleNode.appendChild(styleText);
"
                 "document.getElementsByTagName('head')[0].appendChild(styleNode);
",css];
    NSLog(@"js:
%@",js);
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...