使用JavaScript将CSS注入UIWebView

And*_*nov 5 javascript objective-c javascript-injection uiwebview ios

我试图注入一个本地CSS文件来覆盖网页的样式.该网页显示UIWebView在iOS 中的容器中.但是我无法让我的代码工作.请参阅下面的委托方法的片段.这段代码运行(我可以看到NSLog消息),但我没有在页面上看到它的执行结果.

我知道它不能是我写的CSS,因为在这种情况下,我把页面自己的CSS文件,只是改变了一些颜色.(为了测试这种方法)

-(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");
}
Run Code Online (Sandbox Code Playgroud)

joe*_*ick 9

你的解决方案不起作用,因为

  1. cssNode.href应该是一个URL(即转义和前缀file://),而不是路径
  2. Safari不允许您从远程页面加载本地文件,因为它存在安全风险.

在过去,我通过使用NSURLConnection下载HTML,然后<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];
Run Code Online (Sandbox Code Playgroud)