- 初始化时进行注入
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];
}
标签:alloc,代码,js,NSString,webView,JS,WKWebView,注入
From: https://www.cnblogs.com/wgb1234/p/16724396.html