一、注入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));
}
如有错误请指正。
网友评论