wkwebview注入css和js

一、注入js
wkwebview注入js有两种方式
一种是

WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.userContentController = [[WKUserContentController alloc] init];
NSString *js = @"function myAlert() {\
    alert('这就是js啊');\
}";
WKUserScript *jsUserScript = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[config.userContentController addUserScript:jsUserScript];

另一种是

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
       NSString *js = @"";
     [webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
       
      }];
}

二、注入css
wkwebview并没有直接注入css的方法,所以取了个巧,用js的方法注入了css。
直接上代码了。
下面这一段代码就是要注入的js,而这段代码就是用来将css文件注入到网页中的。

function addNewStyle(newStyle) {
    var styleElement = document.getElementById('styles_js');
    if (!styleElement) {
        styleElement = document.createElement('style');
        styleElement.type = 'text/css';
        styleElement.id = 'styles_js';
        document.getElementsByTagName('head')[0].appendChild(styleElement);
    }
    styleElement.appendChild(document.createTextNode(newStyle));
}

如有错误请指正。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容