PMK
PMK

Reputation: 1

Issue regarding open file from android mobile inside webview

I need to open blob url getting from webview onNavigationRequest. I have tried running javascripts and convert to base64 format but it's not working. I have used webview_flutter: ^4.9.0 with latest fluter SDK.

My code is as per below, i have added javascripts for convert blob link to base64 format but it's not working and not getting any data inside javascriptchannel when click on link to open file.

@override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      // ..addJavaScriptChannel('Mobile',
      //     onMessageReceived: (JavaScriptMessage message) {
      //   Map<String, dynamic> data = jsonDecode(message.message);
      //   if (data['action'] == 'fileDownload') {
      //     saveToFile(data['data']);
      //   }
      // })
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            _showLoader.value = true;
          },
          onPageFinished: (String url) async {
            // Disable long press for non-input elements
            _controller.runJavaScript('''
             (function() {
        document.querySelectorAll('a').forEach(function(element) {
          if (element.href.startsWith('blob:')) {
            element.onclick = function(event) {
              event.preventDefault(); // Prevent default navigation
              fetch(element.href)
                .then(response => response.blob())
                .then(blob => {
                  const reader = new FileReader();
                  reader.onloadend = function() {
                    // Send the base64 string back to Flutter
                    window.flutter_inappwebview.callHandler('handleBlob', reader.result);
                  };
                  reader.readAsDataURL(blob);
                });
            };
          }
        });
      })();
      
            ''');
            /*await _controller.runJavaScript('''
              window.saveBlobToFile = function(blobUrl) {
                return blobUrl;
              };
            ''');*/
            _showLoader.value = false;
            requestManageStoragePermission();
            // Inject custom JavaScript to handle blob URL downloads
          },
          // onNavigationRequest: (NavigationRequest request) async {
          //   if (request.url.contains('blob') ||
          //       request.url.contains('.zip') ||
          //       request.url.contains('.doc')) {
          //     // Handle file downloads
          //     if (await canLaunchUrl(Uri.parse(request.url ?? ''))) {
          //       await launchUrl(Uri.parse(request.url));
          //     }
          //     return NavigationDecision.prevent;
          //   }
          //   return NavigationDecision.navigate;
          // },
        ),
      )
      ..loadRequest(Uri.parse('$myUrl'));
    if (Platform.isAndroid) {
      // or: if (webViewController.platform is AndroidWebViewController)
      final myAndroidController =
          _controller.platform as AndroidWebViewController;

      myAndroidController.setOnShowFileSelector((params) async {
        final result = await FilePicker.platform.pickFiles();

        if (result != null && result.files.single.path != null) {
          final file = File(result.files.single.path!);
          return [file.uri.toString()];
        }
        return []; // Uris
      });
    }
    // Set up the JavaScript handler
    _controller.addJavaScriptChannel(
      'handleBlob',
      onMessageReceived: (JavaScriptMessage message) {
        // Call the function to save the blob data
        _saveBase64ToFile(message.message);
      },
    );
  }

if anyone have idea about it please let me know. Thank you in advace.

Upvotes: 0

Views: 33

Answers (0)

Related Questions