使用JavaScript的UIWebView CSS注入

14 javascript css iphone uiwebview ios

我正在尝试将一个本地css文件注入一个UIWebView,完成加载网站,如谷歌等.

我正在尝试使用JavaScript但没有成功.


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *cssPath = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"styles.css"]];
    NSURL *baseURL = [NSURL fileURLWithPath:cssPath];

    NSString *js = [NSString stringWithFormat:@"var fileref = document.createElement('link');
                    fileref.setAttribute('rel', 'stylesheet');
                    fileref.setAttribute('type', 'text/css');
                    fileref.setAttribute('href', %@);", baseURL];

    [webView stringByEvaluatingJavaScriptFromString:js];
}
Run Code Online (Sandbox Code Playgroud)

谢谢,

Jim*_*m T 20

我有类似的需求.我在捆绑包中有本地html文件,我想以编程方式更改css属性.由于你无法更改bundle中的文件,我想在加载时从应用程序中的变量注入我的css.

下面的代码演示了该技术,只需用您的方法替换获取css,即从文件,plist,代码或db中读取.

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString* css = @"\"@font-face { font-family: 'Chalkboard'; src: local('ChalkboardSE-Regular'); } body { background-color: #F0F0FC; color: #572B00; font-family: Chalkboard;} a { color: #A00; text-decoration: none;}\"";
    NSString* js = [NSString stringWithFormat:
                @"var styleNode = document.createElement('style');\n"
                 "styleNode.type = \"text/css\";\n"
                 "var styleText = document.createTextNode('%@');\n"
                 "styleNode.appendChild(styleText);\n"
                 "document.getElementsByTagName('head')[0].appendChild(styleNode);\n",css];
    NSLog(@"js:\n%@",js);
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}
Run Code Online (Sandbox Code Playgroud)


ric*_*ich 6

要将javascript注入Web视图,您必须在html中明确写入.

这里的一个例子是我在javascript scrollTo函数中写的地方:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
 [webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"  
 "script.type = 'text/javascript';"  
 "script.text = \"function myFunction() { "  
 "window.scrollTo(100,100)"
 "}\";"  
 "document.getElementsByTagName('head')[0].appendChild(script);"];  

 [webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];}
Run Code Online (Sandbox Code Playgroud)

此代码将整个脚本标记和myFunction写入HTML的头部