最近公司项目在iPad上所有js交互都失效了,是因为WKWebView 在iPad上加载手机端的网址时,会自动将该网址转为PC端的网址,所以只需改变WKWebview的userAgent浏览器标识就可以了,附上代码:
.h
#import <WebKit/WebKit.h>
@interface BaseWKWebView : WKWebView
@end
.m
#import "BaseWKWebView.h"
@implementation BaseWKWebView
- (instancetype)initWithFrame:(CGRect)frame configuration:(nonnull WKWebViewConfiguration *)configuration
{
self = [super initWithFrame:frame configuration:configuration];
if (self) {
[self evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id __nullable userAgent, NSError * __nullable error) {
self.customUserAgent = [userAgent stringByReplacingOccurrencesOfString:@"iPad" withString:@"iPhone"];
}];
}
return self;
}
@end
创建WKWebview继承此BaseWKWebView即可
网友评论