【问题标题】:Injecting CSS into UIWebView using JavaScript使用 JavaScript 将 CSS 注入 UIWebView
【发布时间】:2012-02-06 07:13:30
【问题描述】:

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

【问题讨论】:

    标签: javascript objective-c ios uiwebview javascript-injection


    【解决方案1】:

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

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

    【讨论】:

    • 这里没有考虑到的可能性
    • 另外,一个 html 甚至可能没有 head 标签
    • 你能帮助我如何将图标放入输入元素中。 . .
    猜你喜欢
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    相关资源
    最近更新 更多