美文网首页
Flutetr webview加载本地html 无法加载js文件

Flutetr webview加载本地html 无法加载js文件

作者: zb_在路上 | 来源:发表于2020-03-15 12:12 被阅读0次

    Flutter官方的webview_flutter ios中使用的wkwebview来实现的,webview加载本地html 无法加载js文件, 网上找了很多方法都不行、后来发现只要在FlutterWebview initWithFrame方法中加上这一句话就好了,另外注意需要在当前app的沙盒中。

      [configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
    

    完整的代码

    - (instancetype)initWithFrame:(CGRect)frame
                   viewIdentifier:(int64_t)viewId
                        arguments:(id _Nullable)args
                  binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
      if (self = [super init]) {
        _viewId = viewId;
    
        NSString* channelName = [NSString stringWithFormat:@"plugins.flutter.io/webview_%lld", viewId];
        _channel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:messenger];
        _javaScriptChannelNames = [[NSMutableSet alloc] init];
    
        WKUserContentController* userContentController = [[WKUserContentController alloc] init];
        if ([args[@"javascriptChannelNames"] isKindOfClass:[NSArray class]]) {
          NSArray* javaScriptChannelNames = args[@"javascriptChannelNames"];
          [_javaScriptChannelNames addObjectsFromArray:javaScriptChannelNames];
          [self registerJavaScriptChannels:_javaScriptChannelNames controller:userContentController];
        }
    
        NSDictionary<NSString*, id>* settings = args[@"settings"];
    
        WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
          
    //      WKUserScript *script = [[WKUserScript alloc] initWithSource:[self jsString] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
    //      [configuration.userContentController addUserScript:script];
          [configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
          
        configuration.userContentController = userContentController;
        [self updateAutoMediaPlaybackPolicy:args[@"autoMediaPlaybackPolicy"]
                            inConfiguration:configuration];
    
        _webView = [[FLTWKWebView alloc] initWithFrame:frame configuration:configuration];
        _navigationDelegate = [[FLTWKNavigationDelegate alloc] initWithChannel:_channel];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = _navigationDelegate;
        __weak __typeof__(self) weakSelf = self;
        [_channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
          [weakSelf onMethodCall:call result:result];
        }];
    
        if (@available(iOS 11.0, *)) {
          _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
          if (@available(iOS 13.0, *)) {
            _webView.scrollView.automaticallyAdjustsScrollIndicatorInsets = NO;
          }
        }
    
        [self applySettings:settings];
        // TODO(amirh): return an error if apply settings failed once it's possible to do so.
        // https://github.com/flutter/flutter/issues/36228
    
        NSString* initialUrl = args[@"initialUrl"];
        if ([initialUrl isKindOfClass:[NSString class]]) {
          [self loadUrl:initialUrl];
        }
      }
      return self;
    }
    

    android的话增加这句话,容许加载本地文件url

          webView.getSettings().setAllowFileAccessFromFileURLs(true);
    

    以下方法是几种不行的方法尝试;也是作下记录。

    //- (bool)loadUrl:(NSString*)url withHeaders:(NSDictionary<NSString*, NSString*>*)headers {
    //  NSURL* nsUrl = [NSURL URLWithString:url];
    //  if (!nsUrl) {
    //    return false;
    //  }
    //  NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:nsUrl];
    //  [request setAllHTTPHeaderFields:headers];
    ////判断是url,然后使用不同的加载方式
    //  if([url hasPrefix:@"http"]) {
    //      [_webView loadRequest:request];
    //      NSLog(@"zb....%@",@"loadRequest");
    //  }else{
    //      [_webView loadFileURL:nsUrl allowingReadAccessToURL:[nsUrl URLByDeletingLastPathComponent]];
    //
    //      //      NSURL *pathURL = [NSURL fileURLWithPath:url];
    ////        NSURL* nsUrl = [NSURL URLWithString:@"file:///Users/zhoubo5/jdflutter_webview/dart_2_js_web_example/build/web"];
    ////
    ////      NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    ////
    ////      NSString *path = [document stringByAppendingString:@"/web/index.html"];
    ////      NSURL *pathURL = [NSURL fileURLWithPath:path];
    ////      NSString *path1 = [document stringByAppendingString:@"/web"];
    ////      NSURL *pathURL2 = [NSURL fileURLWithPath:path1];
    //
    ////      NSURL *accessURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] objectAtIndex:0];
    ////      [self.webview loadFileURL:self.url allowingReadAccessToURL:accessURL];
    //
    ////       [_webView loadFileURL:pathURL allowingReadAccessToURL:pathURL2];
    //
    //
    //
    ////      //项目中的文件夹路径
    ////      NSString *directoryPath = [NSFileManager appSourceName:@"FeedbackH5" andType:@""];
    ////
    ////      //tmp缓存文件夹路径
    ////      NSString *tmpPath = [KFileManger tmpPath];
    ////
    ////      //新文件夹名字
    ////      NSString *wwwDir =@"www";
    ////
    ////      //tmp文件夹下创建www文件夹
    ////      [KFileManger createDirWithPath:tmpPath andDirectoryName: wwwDir];
    ////
    ////      //tmp中的www文件夹中的路径
    ////      NSString *tmpWWW = [tmpPath stringByAppendingString: wwwDir];
    ////
    ////      //copy文件夹到 tmp/www 路径下
    ////      [KFileManger copyMissingFile:directoryPath toPath:tmpWWW];
    ////
    ////      // 字符 tmp/www/FeedbackH5/pages/feedback.html 全路径
    ////      NSString *tmpWWWFeedback = [tmpWWW stringByAppendingString:@"/FeedbackH5/pages/feedback.html"];
    ////
    ////      //tmp 操作,字符转换成URL
    ////      NSURL *feedbackURL = [NSURL fileURLWithPath:tmpWWWFeedback];
    ////
    ////      //WKWebView加载
    ////      [_webView loadRequest:[NSURLRequest requestWithURL:feedbackURL]];
    //
    ////         WKWebView *webView  =[[WKWebView alloc]initWithFrame:CGRectMake(0, 0, 300, 400)];
    //
    ////      [self.view addSubview:webView];
    //
    ////      [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path isDirectory:NO]]];
    //
    ////// url    __NSCFString *    @"file:///Users/zhoubo5/jdflutter_webview/dart_2_js_web_example/build/web/index.html"    0x000060000263ec30
    ////      NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    ////
    ////  NSString *path = [document stringByAppendingString:@"/park.html"];
    ////
    ////      NSArray *LibraryArray =  NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    ////
    ////      NSString *CachesPath = [[LibraryArray lastObject] stringByAppendingPathComponent:@"Caches"];
    ////
    ////      NSString *accessURLStr = [[[LibraryArray lastObject] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"/web"];
    ////      NSURL *accessURL = [NSURL fileURLWithPath:accessURLStr];
    ////          [_webView loadFileURL:pathURL allowingReadAccessToURL:accessURL];
    //
    ////      NSData *htmlData = [[NSData alloc] initWithContentsOfFile:@"/Users/zhoubo5/jdflutter_webview/dart_2_js_web_example/build/web/index.html"];
    ////            NSData *htmlData = [[NSData alloc] initWithContentsOfFile:path];
    ////
    ////      NSURL* nsUrl3 = [NSURL URLWithString:@"file:///Users/zhoubo5/Library/Developer/CoreSimulator/Devices/7FF29F20-5129-4931-8F79-A95C70CF2895/data/Containers/Data/Application/3DB61D34-D6DC-4CDB-BA2B-305775ECDDCE/Documents/web"];
    //
    ////      if (@available(iOS 9.0, *)) {
    ////          [_webView loadData:htmlData MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:nsUrl3];
    ////      } else {
    ////          // Fallback on earlier versions
    ////      }
    //
    //      NSLog(@"zb....%@",@"loadFileURL");
    //  }
    //  return true;
    //}
    

    相关文章

      网友评论

          本文标题:Flutetr webview加载本地html 无法加载js文件

          本文链接:https://www.haomeiwen.com/subject/oothehtx.html