问题描述
我正在尝试注入一个本地CSS文件来覆盖网页的样式。该网页显示在iOS中的 UIWebView
容器中。但是我无法让我的代码工作。请参阅下面的委托方法的片段。此代码运行(我可以看到 NSLog
消息),但我没有在页面上看到它的执行结果。
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.
我知道它不能是我写的CSS,因为在这种情况下我把页面自己的CSS文件改成了一些颜色。 (为了测试这种方法)
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");
}
推荐答案
您的解决方案不起作用因为
Your solution won't work because
- 你的
cssNode.href
应该是一个URL(即转义并加上前缀file://
),而非路径 - Safari不允许您从远程页面加载本地文件,因为它是安全风险。
- your
cssNode.href
should be a URL (i.e. escaped and prefixed withfile://
), not a path - Safari doesn't let you load local files from a remote page, as it's a security risk.
过去我通过使用NSURLConnection下载HTML,然后添加<$ c $来完成此操作HTML头中的c>< style> 标记。类似于:
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];
这篇关于使用JavaScript将CSS注入UIWebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!