美文网首页iOS开发
WKWebView直接获取网页中的游戏

WKWebView直接获取网页中的游戏

作者: hypercode | 来源:发表于2023-07-20 10:48 被阅读0次

    在你的 ViewController.m 文件中设置 WKWebView:

    #import <WebKit/WebKit.h>
    
    @interface ViewController () <WKScriptMessageHandler>
    @property (nonatomic, strong) WKWebView *webView;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        [userContentController addScriptMessageHandler:self name:@"imageHandler"];
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = userContentController;
        
        self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
        [self.view addSubview:self.webView];
        
        NSURL *url = [NSURL URLWithString:@"https://example.com"];
        [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    }
    
    // 处理从JavaScript发送的消息
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        if ([message.name isEqualToString:@"imageHandler"]) {
            if ([message.body isKindOfClass:[NSString class]]) {
                NSString *base64String = (NSString *)message.body;
                NSData *imageData = [[NSData alloc] initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
                UIImage *image = [UIImage imageWithData:imageData];
                
                // 在这里可以处理或显示提取到的图片了
            }
        }
    }
    
    @end
    
    

    在你的网页中,插入 JavaScript 代码,提取图片并将其转换为 Base64 编码,然后通过 JavaScript 接口发送消息给 WKWebView:

    <html>
      <body>
        <script>
          // 提取图片并将其转换为 Base64 编码
          function extractImage() {
            var imgElement = document.getElementsByTagName('img')[0];
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');
            context.drawImage(imgElement, 0, 0);
            var base64String = canvas.toDataURL();
            
            // 发送消息给原生代码
            window.webkit.messageHandlers.imageHandler.postMessage(base64String);
          }
          
          // 在适当的时候调用提取图片的方法
          extractImage();
        </script>
        <img src="example.jpg" alt="Example Image">
      </body>
    </html>
    
    

    相关文章

      网友评论

        本文标题:WKWebView直接获取网页中的游戏

        本文链接:https://www.haomeiwen.com/subject/zmtzudtx.html