Embedding CSS in a UIWebView using JavaScript

I am trying to introduce a local CSS file to override the style of the webpage. The webpage is presented in a container UIWebViewin iOS. However, I cannot get my code to work. See a snippet of my delegate method below. This code works (I see the message NSLog), but I do not see the results of its execution on the page.

I know that this is not the CSS that I wrote, because in this case I took the pages of my own CSS file and just changed some colors. (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");
}
+5
source share
1 answer

Your solution will not work because

  • cssNode.href URL (.. file://),
  • Safari , .

, HTML NSURLConnection, <style> HTML. - :

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];
+9

All Articles