// // H5View.m // TestGameWeb // // Created by Mac on 2024/1/30. // #import "H5View.h" #import "CircularProgressBar.h" #import #import "CustomView.h" #import "UnityFramework.h" #import @implementation H5View{ WKWebView * webview; WKWebView * webview_1; CircularProgressBar* bar; //奖励按钮进度条 UIView * flyBtn; //飞行奖励按钮节点,也可以用UIButton但要屏蔽事件 UIImageView* flyBg; //飞行奖励闪光背景 UIImageView* rewardBtn; //奖励按钮节点 NSTimer* updateTimer; //动效定时器 CGPoint points[4]; //飞行按钮飞行点位 NSInteger pointIndex; //当前飞行下标 BOOL canFly; //是否可飞行 CGPoint targetPoint; //飞行的下一个点 CGPoint delta; //飞行移动的delta BOOL canCheckTouch; //加这个变量来防止检测点击事件出现多次 BOOL canCT; //点击是否可穿透 NSString* lastUrl; //记录上一次打开的url BOOL inited; //当前view是否被初始化 CGPoint hitTestLocation; //hitest 点击的点 float bgAngle; //飞行按钮背景图的角度 BOOL is_first_btn; //是否是第一次生成网页按钮 int flyCtRate;//飞行按钮穿透概率 float stopTouchTime; int otherH5switch; //是否自动刷h5界面 int H5Refreshtime; //h5刷新默认间隔时间 int Dailyrefreshtimes; //每天h5剩余刷新次数 UIScrollView *scrollView; BOOL is_transparent; BOOL dark_though; NSMutableArray * dark_though_rate; float Dark_stopRefeshTime; float Dark_stopRefeshTime_1; NSMutableArray *dark_H5Refreshtime; //h5刷新默认间隔时间 NSMutableArray *dark_Dailyrefreshtimes; //每天h5剩余刷新次数 NSMutableArray *dark_url_array; BOOL inH5ui; NSMutableArray *light_url_array; BOOL isClickProgress; BOOL isClickFly; int light_though_rate; BOOL isShowFlyBtn; BOOL isShowRewardBtn; BOOL isMultiView; float top_; float height_; BOOL is_gift; int offset_y; int offset_y1; // UITapGestureRecognizer *tapGesture; // UITapGestureRecognizer *tapGesture_1; BOOL in_game; NSMutableArray *web_through_array; NSString* webview_url; NSString* webview_1_url; NSMutableArray *ClickAddtime; BOOL webview_IsCLickAd; BOOL webview_1_IsCLickAd; float web_1_through_time; float web_2_through_time; int dark_webview1_random_refresh_time; int dark_webview2_random_refresh_time; float web_1_disable_time; float web_2_disable_time; } //单利模式 +(id) shared{ static H5View *view = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{view = [[self alloc] init];}); return view; } //初始化页面 -(void)initView{ if (inited)return; [self initFlyBtn]; [self setHidden:YES]; //默认为隐藏状态 [self hideView]; canCheckTouch = true; inited = true; Dark_stopRefeshTime=0; Dark_stopRefeshTime_1=0; dark_though_rate= [NSMutableArray array]; // NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 // target:self // selector:@selector(timerAction:) // userInfo:nil // repeats:YES]; NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES]; // 将 timer 添加到 NSRunLoopCommonModes 模式 [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; CustomView *custom = [[CustomView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]; custom.backgroundColor = [UIColor clearColor]; custom.userInteractionEnabled=YES; [self.window.rootViewController.view addSubview:custom]; // UnityFramework *unityFramework = [UnityFramework getInstance]; // UnityAppController *appController = [unityFramework appController]; // // // 获取 Unity 根节点视图 // UIView *unityRootView = [appController rootView]; // unityRootView.alpha=0.2; } -(void)initWebview:(int)type{ NSLog(@"kkkkkkkkkkkkkkkkkkkkkk%d",type); if(type==2&&!isMultiView) return; if (webview != nil) { // 移除WebView的委托 if(type==1){ webview.navigationDelegate = nil; // 停止加载和清理缓存 [webview stopLoading]; [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]]; [NSURLCache.sharedURLCache removeAllCachedResponses]; // 从视图层次结构中移除WebView [webview removeFromSuperview]; webview = nil; } } if (webview_1 != nil) { // 移除WebView的委托 if(type==2){ webview_1.navigationDelegate = nil; // 停止加载和清理缓存 [webview_1 stopLoading]; [webview_1 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]]; [NSURLCache.sharedURLCache removeAllCachedResponses]; // 从视图层次结构中移除WebView [webview_1 removeFromSuperview]; webview_1 = nil; } } WKWebViewConfiguration *webViewConfiguration = [[WKWebViewConfiguration alloc] init]; if(is_transparent){ webViewConfiguration.allowsInlineMediaPlayback = YES; webViewConfiguration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeAll; NSString *css = @"body { -webkit-user-select: none;user-select: none; }"; NSString *jsCSS = [NSString stringWithFormat:@"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style);", css]; // NSString *js = // @"(function() { " // "var elements = document.querySelectorAll('input, textarea, select'); " // "elements.forEach(function(element) { " // "element.disabled = true; " // "}); " // "})();" // " document.addEventListener('touchstart', function(event) {" // " const target = event.target;" // " if (target.matches('.ad-class') || target.closest('.ad-class')) {" // 替换 '.ad-class' 为广告元素的实际类名 // " setTimeout(function() {" // " const touchCancelEvent = new TouchEvent('touchcancel', {" // " bubbles: true," // " cancelable: true," // " touches: []," // " targetTouches: []," // " changedTouches: event.changedTouches," // " shiftKey: event.shiftKey" // " });" // " target.dispatchEvent(touchCancelEvent);" // " }, 1000);" // " event.preventDefault();" // 禁用默认触摸事件 // " }" // "}, { passive: false });"; NSString *js = @"(function() { " // 禁用所有表单元素 "var elements = document.querySelectorAll('input, textarea, select'); " "elements.forEach(function(element) { " " element.disabled = true; " "}); " // 禁用所有音频和视频 "document.querySelectorAll('audio, video').forEach(function(el) { " " el.muted = true; " " el.pause(); " "}); " // 处理触摸事件,阻止广告类元素的触摸 "document.addEventListener('touchstart', function(event) {" " const target = event.target;" " if (target.matches('.ad-class') || target.closest('.ad-class')) {" // 替换 '.ad-class' 为广告元素的实际类名 " setTimeout(function() {" " const touchCancelEvent = new TouchEvent('touchcancel', {" " bubbles: true," " cancelable: true," " touches: []," " targetTouches: []," " changedTouches: event.changedTouches," " shiftKey: event.shiftKey" " });" " target.dispatchEvent(touchCancelEvent);" " }, 1000);" " event.preventDefault();" // 禁用默认触摸事件 " }" "}, { passive: false });" "})();"; NSString *combinedJS = [NSString stringWithFormat:@"%@ %@", jsCSS, js]; WKUserScript *userScript = [[WKUserScript alloc] initWithSource:combinedJS injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO]; [webViewConfiguration.userContentController addUserScript:userScript]; } if(type==1) { webview = [[WKWebView alloc] initWithFrame:self.frame configuration:webViewConfiguration]; [self addSubview:webview]; webview.allowsLinkPreview = NO; [self insertSubview:webview atIndex:0]; // webview .alpha=0.5; } if(type==2){ webview_1 = [[WKWebView alloc] initWithFrame:self.frame configuration:webViewConfiguration]; [self addSubview:webview_1]; webview_1.allowsLinkPreview = NO; [self insertSubview:webview_1 atIndex:0]; } webview.navigationDelegate=self; webview_1.navigationDelegate=self; // webview.tag = 1; // webview_1.tag = 2; webview.UIDelegate=self; webview_1.UIDelegate=self; // 将WebView添加到当前视图的最后面 // [self insertSubview:webview atIndex:0]; // 将WebView添加到当前视图的最后面 //[self insertSubview:webview_1 atIndex:1]; // if (webview.superview == nil) // [self ChangeViewRect:!is_transparent]; // [self showWebview:@"https://baidu.com"]; } //- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { // // NSLog(@"pppppppppppppppppJavaScript 点击了链接: "); // if ([message.name isEqualToString:@"linkClicked"]) { // NSString *urlString = message.body; // // // // 在这里处理链接点击,例如加载链接 // NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]; // [webview loadRequest:request]; // } //} - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures { if (!navigationAction.targetFrame.isMainFrame) { [webView loadRequest:navigationAction.request]; } return nil; } //当前view的显/隐 -(void)showView:(BOOL)show{ if (!show){ [self hideView]; }else{ //[self setHidden:NO]; // NSLog(@"xianshimingchuantouuuuuuuuuuuuuu1----%d", inH5ui); if(!inH5ui) return; // NSLog(@"xianshimingchuantouuuuuuuuuuuuuu2----%d", show); if(is_transparent){ webview.hidden=YES; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@""] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [webview loadRequest:request]; [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayShowH5) object:nil]; [self performSelector:@selector(delayShowH5) withObject:nil afterDelay:1.5]; } [self.superview bringSubviewToFront:self]; is_transparent=NO; if (isShowRewardBtn) { [rewardBtn setHidden:NO]; } else { [rewardBtn setHidden:YES]; } [self showWebview:lastUrl]; //打开webview时url为上一次 [self ChangeViewRect:true]; [self startFlyAnim]; //每一次显示时强行执行飞行按钮的动画 if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { self .alpha=1; } } } //隐藏view -(void)hideView{ [self stopUpdate]; if(!is_transparent){ webview.hidden=YES; webview_1.hidden=YES; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@""] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [webview loadRequest:request]; [webview_1 loadRequest:request]; [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayShowH5) object:nil]; [self performSelector:@selector(delayShowH5) withObject:nil afterDelay:0.5]; } is_transparent=YES; [self.superview sendSubviewToBack:self]; self.userInteractionEnabled=TRUE; [flyBtn setHidden:YES]; [rewardBtn setHidden:YES]; Dark_stopRefeshTime=0; Dark_stopRefeshTime_1=0; [self showDarkWebview:1]; [self showDarkWebview:2]; [self ChangeViewRect:false]; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { self .alpha=0; } } -(void)delayShowH5{ webview.hidden=NO; webview_1.hidden=NO; } -(void)setInH5View:(BOOL)flag{ // NSLog(@"aaaaaaaaaaaaaaaaaa%d",flag); inH5ui=flag; } -(void)upDataH5times:(char*)weblink times:(int)times is_dark:(BOOL)is_dark{ NSString *myNSString = [[NSString alloc] initWithUTF8String:weblink]; if(is_dark){ for (int counter = 0; counter < dark_url_array.count; counter++) { if( [dark_url_array[counter][0] isEqualToString:myNSString]){ dark_url_array[counter][2]=@(times); dark_though_rate[[dark_url_array[counter][4] intValue]-1]=@([dark_url_array[counter][3] intValue]); break; } } } else{ for (int counter = 0; counter < light_url_array.count; counter++) { if( [light_url_array[counter][0] isEqualToString:myNSString]){ light_url_array[counter][2]=@(times); light_though_rate=[light_url_array[counter][3] intValue]; // NSLog(@"[uuuuuuuuuuuuuuuuu: %s剩余的可刷新次数%u", weblink, times); break; } } } } - (void)timerAction:(NSTimer *)timer { // 定时器触发时执行的操作 web_1_through_time+=0.1; web_2_through_time+=0.1; stopTouchTime+=0.1; Dark_stopRefeshTime+=0.1; Dark_stopRefeshTime_1+=0.1; if(is_transparent){ if([dark_Dailyrefreshtimes[0] intValue]>0&&Dark_stopRefeshTime>dark_webview1_random_refresh_time){ dark_Dailyrefreshtimes[0]=@([dark_Dailyrefreshtimes[0] intValue]-1); UnitySendMessage("WebviewManager", "H5AutoRefresh","dark_Dailyrefreshtimes|0" ); Dark_stopRefeshTime=0; dark_webview1_random_refresh_time=[dark_H5Refreshtime[0] intValue] + arc4random_uniform([dark_H5Refreshtime[1] intValue] - [dark_H5Refreshtime[0] intValue] + 1); NSLog(@"hhhhhhhhhhhh3333333kkkk%d",dark_webview1_random_refresh_time); [self showDarkWebview:1]; [self ChangeViewRect:false]; } if([dark_Dailyrefreshtimes[1] intValue]>0&&Dark_stopRefeshTime_1>dark_webview2_random_refresh_time){ dark_Dailyrefreshtimes[1]=@([dark_Dailyrefreshtimes[1] intValue]-1); UnitySendMessage("WebviewManager", "H5AutoRefresh","dark_Dailyrefreshtimes|1" ); Dark_stopRefeshTime_1=0; dark_webview2_random_refresh_time=[dark_H5Refreshtime[2] intValue] + arc4random_uniform([dark_H5Refreshtime[3] intValue] - [dark_H5Refreshtime[2] intValue] + 1); NSLog(@"hhhhhhhhhhhh3333333kkkk%d",dark_webview2_random_refresh_time); [self showDarkWebview:2]; [self ChangeViewRect:false]; } } else{ if(otherH5switch!=1 ) return; if(Dailyrefreshtimes<=0 ) return; if(stopTouchTime>H5Refreshtime){ UnitySendMessage("WebviewManager", "H5AutoRefresh","Dailyrefreshtimes" ); [self showWebview:lastUrl]; [self ChangeViewRect:true]; stopTouchTime=0; Dailyrefreshtimes--; } } } // 处理网页开始加载 //- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { // NSLog(@"WebView with tag %ld started loading", (long)webView.tag); // [self injectJavaScriptIntoWebView:webView]; // 在开始加载时重新注入 JavaScript //} // //// 处理网页加载完成 //- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { // NSLog(@"WebView with tag %ld finished loading", (long)webView.tag); // [self injectJavaScriptIntoWebView:webView]; // 在加载完成时重新注入 JavaScript //} - (void)yourMethodToCall { if(!is_transparent) { webview.hidden=NO; } } //显示webview -(void)showWebview:(NSString*)url{ if (is_transparent) return; //view在隐藏状态下不显示webview,因为目前只需要处理明webview 的显示。 // NSLog(@"xianshimingchuantouuuuuuuuuuuuuu3----%d"); [self initWebview:1]; float maxvalue=0; for (int counter = 0; counter < light_url_array.count; counter++) { if([light_url_array[counter][2] intValue]>0 ){ maxvalue+=[light_url_array[counter][1] floatValue]; } } float random3 ; float rate=0; if(maxvalue>0){ random3=arc4random_uniform(maxvalue); for (int counter = 0; counter < light_url_array.count; counter++) { if([light_url_array[counter][2] intValue]==0) continue; float myFloat = [light_url_array[counter][1] floatValue]; light_though_rate=[light_url_array[counter][3] intValue]; rate+=myFloat; if(random3<=rate){ url=light_url_array[counter][0]; light_url_array[counter][2]=@([light_url_array[counter][2] floatValue]-1); break; } } } else{ random3=arc4random_uniform(100); for (int counter = 0; counter < light_url_array.count; counter++) { float myFloat = [light_url_array[counter][1] floatValue]; light_though_rate=[light_url_array[counter][3] intValue]; rate+=myFloat; if(random3<=rate){ url=light_url_array[counter][0]; break; } } } // NSLog(@"xianshimingchuantouuuuuuuuuuuuuu3----%@",url); UnitySendMessage("WebviewManager", "SendH5Event", "test"); stopTouchTime=0; //@"https://tool.lu/timestamp/?ivk_sa=1023231z"@"https://fanyi.baidu.com/ if(url.length!=0) webview_url=url; else return; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] ]; [webview loadRequest:request]; webview_IsCLickAd=YES; if (webview.superview == nil) [self insertSubview:webview atIndex:0]; UnitySendMessage("WebviewManager", "H5AutoRefresh",[[url stringByAppendingString:@"|h5"] UTF8String]); } -(void)showDarkWebview:(int)type{ if(!is_gift) return; [self initWebview:type]; NSString* url=@""; UnitySendMessage("WebviewManager", "SendH5Event", "test"); float maxvalue=0; float random3 ; float rate=0; if(type==1){ for (int counter = 0; counter < dark_url_array.count; counter++) { if([dark_url_array[counter][2] intValue]>0 ){ if([dark_url_array[counter][4] intValue]!=1 ) continue; maxvalue+=[dark_url_array[counter][1] floatValue]; } } if(maxvalue>0){ random3=arc4random_uniform(maxvalue); for (int counter = 0; counter < dark_url_array.count; counter++) { if([dark_url_array[counter][2] intValue]<=0) continue; if([dark_url_array[counter][4] intValue]!=1 ) continue; float myFloat = [dark_url_array[counter][1] floatValue]; dark_though_rate[[dark_url_array[counter][4] intValue]-1]=@([dark_url_array[counter][3] intValue]); rate+=myFloat; if(random3<=rate){ url=dark_url_array[counter][0]; dark_url_array[counter][2]=@([dark_url_array[counter][2] floatValue]-1); break; } } } else{ random3=arc4random_uniform(100); for (int counter = 0; counter < dark_url_array.count; counter++) { if([dark_url_array[counter][4] intValue]!=1 ) continue; float myFloat = [dark_url_array[counter][1] floatValue]; dark_though_rate[[dark_url_array[counter][4] intValue]-1]=@([dark_url_array[counter][3] intValue]); rate+=myFloat; if(random3<=rate){ url=dark_url_array[counter][0]; break; } } } NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]]; if(url.length!=0) webview_url=url; else return; // NSLog(@"33333333333333333%@",url); webview_IsCLickAd=NO; [webview loadRequest:request]; } else if(type==2){ if(!isMultiView) return; for (int counter = 0; counter < dark_url_array.count; counter++) { if([dark_url_array[counter][2] intValue]>0 ){ if([dark_url_array[counter][4] intValue]!=2 ) continue; maxvalue+=[dark_url_array[counter][1] floatValue]; } } rate=0; if(maxvalue>0){ random3=arc4random_uniform(maxvalue); for (int counter = 0; counter < dark_url_array.count; counter++) { if([dark_url_array[counter][2] intValue]<=0) continue; if([dark_url_array[counter][4] intValue]!=2 ) continue; float myFloat = [dark_url_array[counter][1] floatValue]; // dark_though_rate=[dark_url_array[counter][3] intValue]; dark_though_rate[[dark_url_array[counter][4] intValue]-1]=@([dark_url_array[counter][3] intValue]); rate+=myFloat; if(random3<=rate){ url=dark_url_array[counter][0]; dark_url_array[counter][2]=@([dark_url_array[counter][2] floatValue]-1); break; } } } else{ random3=arc4random_uniform(100); for (int counter = 0; counter < dark_url_array.count; counter++) { if([dark_url_array[counter][4] intValue]!=2 ) continue; float myFloat = [dark_url_array[counter][1] floatValue]; dark_though_rate[[dark_url_array[counter][4] intValue]-1]=@([dark_url_array[counter][3] intValue]); rate+=myFloat; if(random3<=rate){ url=dark_url_array[counter][0]; break; } } } if(url.length!=0) webview_1_url=url; else return; NSMutableURLRequest *request_1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] ]; webview_1_IsCLickAd=NO; [webview_1 loadRequest:request_1]; // NSLog(@"333333333333333331%@",url); } UnitySendMessage("WebviewManager", "H5AutoRefresh",[[url stringByAppendingString:@"|h6"] UTF8String]); } //隐藏webview -(void)hideWebview{ [webview removeFromSuperview]; } //设置飞行进度条进度 -(void)setIconProgress:(float)value{ [bar setProgress:value]; // NSLog(@"bbbbbbbbbbbbbbbbbbbbb%f",value); if(value>=1){ UnitySendMessage("WebviewManager", "TouchClickPoint", "finish"); } } //初始化飞行按钮 -(void)initFlyBtn{ flyBtn = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; [self addSubview:flyBtn]; //飞行闪光底图 flyBg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"7"]]; flyBg.frame = CGRectMake(0, 0, 100, 100); [flyBtn addSubview:flyBg]; [flyBtn setUserInteractionEnabled:NO]; UIImageView* icon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"3"]]; icon.frame = CGRectMake(30, 30, 139*0.35, 97*0.35); [flyBtn addSubview:icon]; //飞行点位 float sw = self.frame.size.width; float sh = self.frame.size.height; points[0] = CGPointMake(sw * 0.5,0); points[1] = CGPointMake(-20,sh * 0.25); points[2] = CGPointMake(sw - flyBtn.frame.size.width+20,sh * 0.5); points[3] = CGPointMake(-20,sh - 220); } //执行飞行按钮的动画 -(void)startFlyAnim{ if (!isShowFlyBtn) { flyBtn.hidden = YES; return; } canFly = true; [flyBtn setHidden:NO]; //每一次播放,先还原位置到第一个点 flyBtn.transform = CGAffineTransformMakeTranslation(points[0].x, points[0].y); pointIndex = 0; [self flyAnim]; // float random3 = arc4random_uniform(100) ; // if(random3is_transparent) { // // NSLog(@"Element info11111111122223333: %d", Dark_stopRefeshTime); // UnitySendMessage("WebviewManager", "ClickAdEvent", [[webview_url stringByAppendingString:@"|h6"] UTF8String]); // // Dark_stopRefeshTime-=[ClickAddtime[0] intValue]; // if(!webview_IsCLickAd) Dark_stopRefeshTime-= [self randomValueBetween]; // webview_IsCLickAd=YES; // // NSLog(@"Element info11111111122223333: %d", Dark_stopRefeshTime); // } // else { // UnitySendMessage("WebviewManager", "ClickAdEvent", [[webview_url stringByAppendingString:@"|h5"] UTF8String]); // } // // } //// else { //// NSLog(@"Result does not contain 'iframe' string"); //// } // } // }]; //} - (int)randomValueBetween{ int lowerBound =[ClickAddtime[0] intValue]; int upperBound =[ClickAddtime[1] intValue]; return lowerBound + arc4random_uniform((upperBound - lowerBound + 1)); } - (void)handleTap_1:(UITapGestureRecognizer *)sender { CGPoint location = [sender locationInView:webview_1]; NSLog(@"Tap detected at location: %@", NSStringFromCGPoint(location)); // 模拟点击事件传递给第二个 WKWebView NSString *js = [NSString stringWithFormat:@"\ var element = document.elementFromPoint(%f, %f);\ if (element) {\ var elementType = element.tagName.toLowerCase();\ var elementName = element.getAttribute('id') || element.getAttribute('class') || 'no-name';\ console.log('Element info: ' + elementType + ' ' + elementName);\ var events = ['mousedown', 'mouseup', 'click'];\ events.forEach(function(eventType) {\ var event = new MouseEvent(eventType, {\ bubbles: true,\ cancelable: true,\ view: window,\ clientX: %f,\ clientY: %f\ });\ element.dispatchEvent(event);\ });\ elementType + ' ' + elementName;\ } else {\ 'no-element';\ }\ ", location.x, location.y, location.x, location.y]; [webview_1 evaluateJavaScript:js completionHandler:^(id result, NSError *error) { if (error) { // NSLog(@"Error simulating mouse events1111111112222: %@", error); } else { // NSLog(@"Element info1111111112222: %@", result); // 判断 result 是否包含 iframe 字符串 if ([result isKindOfClass:[NSString class]] && [(NSString *)result containsString:@"iframe"]) { // NSLog(@"Element info11111111122223333: %d", Dark_stopRefeshTime_1); UnitySendMessage("WebviewManager", "ClickAdEvent", [[webview_1_url stringByAppendingString:@"|h6"] UTF8String]); if(!webview_1_IsCLickAd) Dark_stopRefeshTime_1-=[self randomValueBetween]; webview_1_IsCLickAd=YES; // NSLog(@"Element info11111111122223333: %d", Dark_stopRefeshTime_1); } // else { // NSLog(@"Result does not contain 'iframe' string"); // } } }]; } //hitTest 能在不接受点击事件的view也能捕获多点位的信息 - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { hitTestLocation = point; // NSLog(@"Hit point11111110 x: %f, y:%f", hitTestLocation.x, hitTestLocation.y); // if(inH5ui&& hitTestLocation.y<100){ // hitTestLocation.y+=66; // } // if (canCheckTouch){ //NSLog(@"Hit point11111112 x: %f, y:%f", hitTestLocation.x, hitTestLocation.y); [self checkPointInsideBtn:hitTestLocation]; [self delayInvoke:0.3 cb:^(void){ self->canCheckTouch = YES; }];//加个定时器来防止出发多次检测点击 CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width; // 获取屏幕高度 CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height; NSString *jsCode = [NSString stringWithFormat:@"%f|%f",hitTestLocation.x/screenWidth, hitTestLocation.y/screenHeight]; if (dark_though){ // NSLog(@"Hit point1111113 x: %f, y:%f", hitTestLocation.x, hitTestLocation.y); UnitySendMessage("WebviewManager", "TouchClickPoint",[jsCode UTF8String]); } } canCheckTouch = false; // if(is_transparent&&dark_though){ // if(point.y>self.frame.size.height){ // point.y-=top_; // } // } // if(tapGesture==nil) { // tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; // // tapGesture_1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap_1:)]; // // } UIView* touchedView; int click_web=1; if(!dark_though){ touchedView=[super hitTest:point withEvent:event]; } else{ // NSLog(@"[ggggggggggggggggggg21: %@剩余的可刷新次数", web_through_array[0]); // NSLog(@"[ggggggggggggggggggg21: %@剩余的可刷新次数", web_through_array[1]); // float random_ = arc4random_uniform(100) ; // random_=0;//zhushi if(!is_transparent|| random_<[web_through_array[0] intValue]){ // if(true){ touchedView=[webview hitTest:point withEvent:event]; // tapGesture.delegate=touchedView; // [touchedView addGestureRecognizer:tapGesture]; } else { touchedView=[webview_1 hitTest:point withEvent:event]; click_web=2;//quxiaozhushi // tapGesture_1.delegate=touchedView; // [touchedView addGestureRecognizer:tapGesture_1]; } } // [self.webView2 addGestureRecognizer:tapGesture]; if(is_transparent&&dark_though){//暗穿透 float random3 = arc4random_uniform(100) ; // NSLog(@"eeeeeeeeeeeeeeeeeee%i",dark_though_rate); // random3=0;//zhushi // NSLog(@"Point coordinates: max = %f,",self.bounds.size.width); if(isMultiView){ if(click_web==1){ if(random3< [dark_though_rate[0] intValue]){ // NSLog(@"触发点击:%f",web_1_through_time); // NSLog(@"eeeeeeeeeeeeeeeeeee:%f",web_1_disable_time); if(web_1_through_time<0){ // NSLog(@"触发点击,时间小于0:%f",web_1_through_time); return touchedView; } else if(web_1_through_timeisShowFlyBtn) { UnitySendMessage("WebviewManager", "ObjC_TouchClick", "flyBtn"); } if(flyBtn.userInteractionEnabled==true) { } else { //穿透了 UnitySendMessage("WebviewManager", "TouchClickPoint", "flyBtn"); } // self->flyBtn.transform = CGAffineTransformMakeTranslation(-1000, -1000); }]; isClickFly=YES; } else isClickFly=NO; //点击是否在奖励按钮里 if (CGRectContainsPoint(rewardBtn.frame, point)){ //NSLog(@"Inside rewardBtn"); [self delayInvoke:0.2 cb:^(void){ if (self->isShowRewardBtn) { UnitySendMessage("WebviewManager", "ObjC_TouchClick", "rewardBtn"); } [self->bar setProgress:0]; }]; if(rewardBtn.userInteractionEnabled==true) { } else { //穿透了 UnitySendMessage("WebviewManager", "TouchClickPoint", "rewardBtn"); [bar setProgress:0]; } isClickProgress=YES; } else isClickProgress=NO; } //设置可穿透字段 -(void)enableCT:(BOOL)flag{ // NSLog(@"Native enableCT: %d",flag); canCT = flag; [rewardBtn setUserInteractionEnabled:!flag]; //[flyBtn setUserInteractionEnabled:!flag]; } -(void)setClickView{ in_game=YES; } //延迟执行逻辑 -(void)delayInvoke:(float)delay cb:(dispatch_block_t)cb{ NSTimeInterval delayInSeconds = delay; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), cb); } //飞行按钮隐/藏 -(void)showFlyBtn:(BOOL)flag{ //NSLog(@"showFlyBtn: %d", flag); //[flyBtn setHidden:!flag]; if (flag){ [self startFlyAnim]; }else{ [self stopFlyAnim]; } } -(void)setFlyBtnTag:(BOOL)isShow{ if(!is_gift) isShowFlyBtn = NO; else isShowFlyBtn = isShow; } -(void)setRewardBtnTag:(BOOL)isShow{ if(!is_gift) isShowRewardBtn = NO; else isShowRewardBtn = isShow; } -(void)SetOffset:(int)offsety offset_y1:(int)offsety1 { // NSLog(@"barry ChangeViewRect-==== %d, %d",offset_y,offset_y1); offset_y = offsety; offset_y1 = offsety1; } @end