Injecting CSS into UIWebView using JavaScript
Asked Answered
T

1

5

I am attempting to inject a local CSS file to override the styling of a webpage. The webpage is presented in a UIWebView container in iOS. However I am not able to get my code to work. See the snippet of my delegate method below. This code runs (I can see the NSLog message) but I do not see the results of it's execution on the page.

I know it can't be the CSS I wrote because in this case I took the pages own CSS file and simply changed some colors. (In order to test this method)

-(void)webViewDidFinishLoad:(UIWebView *)webView 
{
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *cssPath = [path stringByAppendingPathComponent:@"reader.css"];
    NSString *js = [NSString stringWithFormat:@"var headID = document.getElementsByTagName('head')[0];var cssNode = document.createElement('link');cssNode.type = 'text/css';cssNode.rel = 'stylesheet';cssNode.href = '%@';cssNode.media = 'screen';headID.appendChild(cssNode);", cssPath];
    [webView stringByEvaluatingJavaScriptFromString:js];
    NSLog(@"webViewDidFinishLoad Executed");
}
Thermosetting answered 9/1, 2012 at 19:4 Comment(0)
D
9

Your solution won't work because

  1. your cssNode.href should be a URL (i.e. escaped and prefixed with file://), not a path
  2. Safari doesn't let you load local files from a remote page, as it's a security risk.

In the past I've done this by downloading the HTML using an NSURLConnection, and then adding a <style> tag in the HTML head. Something like:

NSString *pathToiOSCss = [[NSBundle mainBundle] pathForResource:@"reader" ofType:@"css"];
NSString *iOSCssData = [NSString stringWithContentsOfFile:pathToiOSCss encoding:NSUTF8StringEncoding error:NULL];
NSString *extraHeadTags = [NSString stringWithFormat:@"<style>%@</style></head>", iOSCssData];
html = [uneditedHtml stringByReplacingOccurrencesOfString:@"</head>" withString:extraHeadTags];

[webView loadHTMLString:html baseURL:url];
Dire answered 9/1, 2012 at 23:20 Comment(3)
this does not take into account the possibility of </HEAD>Pinkham
also, a html may not even have a head tagPinkham
can you please help me in how to Put icon inside input element . . .Putdown

© 2022 - 2024 — McMap. All rights reserved.