最近公司項目在iPad上所有js交互都失效了,是因為WKWebView 在iPad上加載手機端的網(wǎng)址時,會自動將該網(wǎng)址轉(zhuǎn)為PC端的網(wǎng)址,所以只需改變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
創(chuàng)建WKWebview繼承此BaseWKWebView即可