Injecting CSS into UIWebView using JavaScript

橙三吉。 提交于 2019-11-30 05:26:05

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