iPad上WKWebView js交互失效

最近公司项目在iPad上所有js交互都失效了,是因为WKWebView 在iPad上加载手机端的网址时,会自动将该网址转为PC端的网址,所以只需改变wkwebview的userAgent浏览器标识就可以了,附上代码:

.h

#import <WebKit/WebKit.h>
@interface WhzxWebView : WKWebView

@end

.m

#import "WhzxWebView.h"

@implementation WhzxWebView

- (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继承此webview即可

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