WKWebView 注入JS代码

  1. 初始化时进行注入
    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];

  1. 页面加载完毕进行注入(当然也可以使用初始化时注入,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];
}
posted @ 2022-09-23 21:13  CoderWGB  阅读(1122)  评论(0编辑  收藏  举报