WKWebView 注入JS代码
- 初始化时进行注入
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
//实际上注入js文件和注入js代码字符串没有区别,因为也要把JS文件读取为字符串进行调用
NSString *js = [[NSBundle mainBundle] pathForResource:@"demo/canvas.js" ofType:nil];
NSData *jsData=[NSData dataWithContentsOfFile:js];
NSString *jsString = [[NSString alloc] initWithData:jsData encoding:NSUTF8StringEncoding];
WKUserScript *jsScript = [[WKUserScript alloc]initWithSource:jsString injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
[config.userContentController addUserScript:jsScript];
_webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
- 页面加载完毕进行注入(当然也可以使用初始化时注入,
injectionTime
改为WKUserScriptInjectionTimeAtDocumentEnd
),一般是先在start时注入,end时进行调用
//便利宏: 避免书写大量的反斜杠转义或者换行
#define JS(...) [[NSString alloc] initWithCString:#__VA_ARGS__ encoding:NSUTF8StringEncoding]
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
self.title = webView.title;
//注入js
[webView evaluateJavaScript:JS(
alert('你好,JS');
console.log('hello JS');
) completionHandler:nil];
}
未经作者授权,禁止转载
本文来自博客园,作者:CoderWGB,转载请注明原文链接:https://www.cnblogs.com/wgb1234/p/16724396.html
THE END