欢迎使用Markdown编辑器写博客

本Markdown编辑器使用[StackEdit][6]修改而来,用它写博客,将会带来全新的体验哦:

使用WKwebVIew,创建这个对象,代码如下

** WKUserScript *script = [[WKUserScript alloc]initWithSource:@”” injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];

[config.userContentController addUserScript:script];

WKWebView *web = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) configuration:config];

web.backgroundColor = [UIColor yellowColor];

web.navigationDelegate = self;

web.UIDelegate = self;

self.webView = web;

[self.view addSubview:web];

NSString *filrStr = [[NSBundle mainBundle] pathForResource:@”js” ofType:@”html”];

NSURL *url = [NSURL fileURLWithPath:filrStr];

[web loadFileURL:url allowingReadAccessToURL:url];

[[web configuration].userContentController addScriptMessageHandler:self name:@”jsCallOC”];**

在网页加载完成后调用这个回调函数,并在里面注入JS代码

/* 网页加载完成/

-(void)webView:(WKWebView )webView didFinishNavigation:(WKNavigation)navigation{

// NSString *butValueJS = @”document.getElementById(‘buttonJS’).innerText”;

NSString *butValueJS =

@”var button = document.getElementById(‘buttonJS’);button.οnclick=function getImages(){window.webkit.messageHandlers.jsCallOC.postMessage({body: ‘goodsId=1212’});}”;

[webView evaluateJavaScript:butValueJS completionHandler:^(id _Nullable response, NSError * _Nullable error) {

}];

}

下面是截图

a7465209269258a45e522a3b091ce49b.png

b172b72beb6978d248985f693180792c.png

/* 接收JS中方法执行事件。/

-(void)userContentController:(WKUserContentController )userContentController didReceiveScriptMessage:(WKScriptMessage)message{

NSLog(@”message.body == %@”,message.name);

[self JCtoOC:message];

}

-(void)JCtoOC:(id)body{

NSLog(@”js调用我的..”);

}

最后在这里接收JS执行的事件

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐