使用JavaScript将CSS注入UIWebView

Injecting CSS into UIWebView using JavaScript

本文关键字:注入 UIWebView CSS JavaScript 使用      更新时间:2023-09-26

我正试图注入一个本地CSS文件来覆盖网页的样式。该网页显示在iOS中的UIWebView容器中。但是,我无法使我的代码正常工作。请参阅下面我的委托方法的片段。这段代码运行(我可以看到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");
}

您的解决方案无法工作,因为

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

在过去,我使用NSURLConnection下载HTML,然后在HTML头中添加<style>标记。类似于:

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