WKWebView直接获取网页中的游戏

在你的 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>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,566评论 8 265
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,136评论 1 32
  • WKWebView 对象可以显示交互式Web内容,例如应用内浏览器。你可以使用 WKWebView 类将Web内容...
    独木舟的木阅读 1,231评论 0 3
  • 开发小知识(一)[https://www.jianshu.com/p/5a4ba3c165b9] 开发小知识(二)...
    ZhengYaWei阅读 837评论 0 2
  • 最近一朋友正准备跳槽,就从各处搜索整理一些基础,便于朋友复习,也便于自己复习查看. 1. 回答person的ret...
    smile丽语阅读 1,787评论 0 7