iOS 10.3 wkwebview WKUserScript 无法成功注入本地js文件的问题

在iOS 10.3环境下,WKWebView遇到WKUserScript无法成功注入本地JavaScript文件的问题,导致Safari调试显示JS未注入。与iOS 11系统对比,此问题显得独特,寻求解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

NSString *runtimejs = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"runtime" ofType:@".js"] encoding:NSUTF8StringEncoding error:nil];
    NSString *vpimjs = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"browser-bundle" ofType:@".js"] encoding:NSUTF8StringEncoding error:nil];
    NSString *jsall = [NSString stringWithFormat:@"%@ %@", runtimejs, vpimjs];
    WKUserScript *script = [[WKUserScript alloc] initWithSource:jsall injectionTime:(WKUserScriptInjectionTimeAtDocumentStart) forMainFrameOnly:YES];
    
    WKUserContentController *userContent = [[WKUserContentController alloc] init];
    [userContent addUserScript:script];
    [userContent addScriptMessageHandler:self name:@"NativeMethod"];
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    [configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
    [configuration setUserContentController:userContent];
    
    self.web = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) configuration:configuration];
    
    NSString *htmlpath = [[NSBundle mainBundle] pathForResource:@"local" ofType:@".html"];
    NSString *localhtml = [NSString stringWithContentsOfFile:htmlpath encoding:NSUTF8StringEncoding error:nil];
    [self.web loadHTMLString:localhtml baseURL:[NSURL fileURLWithPath:htmlpath isDirectory:YES]];
    
    self.web.UIDelegate = self;
    self.web.navigationDelegate = self;
    [self.view addSubview:self.web];
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=TypeError: undefined is not an object (evaluating 'window.VPIM.default'), WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred, WKJavaScriptExceptionColumnNumber=30}

根据Safari连调js文件根本没有注入进去,  在11上正确注入,征集撸友指点回复~!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值