美文网首页webview&js
wkwebview注入css和js

wkwebview注入css和js

作者: 边河 | 来源:发表于2018-11-13 14:20 被阅读155次

一、注入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));
}

如有错误请指正。

相关文章

网友评论

    本文标题:wkwebview注入css和js

    本文链接:https://www.haomeiwen.com/subject/wbmkfqtx.html