IOS OC向h5注入JS代码,知道h5的页面按钮ID,向该按钮添加点击事件

本文介绍如何使用WKWebView修改Markdown编辑器,通过编写代码实现自定义功能,提升博客写作体验。详细展示了从创建WKWebView对象、加载自定义JS文件到注入JS代码并实现与Objective-C交互的过程,最终接收JS执行事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

欢迎使用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.onclick=function getImages(){window.webkit.messageHandlers.jsCallOC.postMessage({body: ‘goodsId=1212’});}”;

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

  • 下面是截图
  • 图片中这个要设置,具体设置什么随自己,要和下面的注入代码一致即可
  • 这里写图片描述
    /* 接收JS中方法执行事件。 /
    -(void)userContentController:(WKUserContentController )userContentController didReceiveScriptMessage:(WKScriptMessage )message{
    NSLog(@”message.body == %@”,message.name);

    [self JCtoOC:message];
    }
    -(void)JCtoOC:(id)body{
    NSLog(@”js调用我的..”);
    }
    最后在这里接收JS执行的事件


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值