Skip to content
This repository has been archived by the owner on Mar 14, 2023. It is now read-only.

Bug fix callJsMethod: Encode/decode JSON when passing data between languages #82

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions lib/src/controller/impl/mobile.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import 'dart:async' show Future;
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
Expand Down Expand Up @@ -127,9 +129,17 @@ class WebViewXController extends ChangeNotifier

// (MOBILE ONLY) Unquotes response if necessary
//
// In the mobile version responses from Js to Dart come wrapped in single quotes (')
// The web works fine because it is already into it's native environment
return HtmlUtils.unQuoteJsResponseIfNeeded(result);
// The web works fine because it is already into its native environment
// but on mobile we need to parse the result
if (Platform.isAndroid) {
// On Android `result` will be JSON, so we decode it
return json.decode(result);
} else {
/// TODO: make sure this works on iOS
// In the iOS version responses from JS to Dart come wrapped in single quotes (')
// Note that the supported types are more limited because of connector.evaluateJavascript
return HtmlUtils.unQuoteJsResponseIfNeeded(result);
}
}

/// This function allows you to evaluate 'raw' javascript (e.g: 2+2)
Expand Down
10 changes: 4 additions & 6 deletions lib/src/utils/html_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,10 @@ class HtmlUtils {
}

for (final param in params) {
args.write(addSingleQuotes(param.toString()));
// Encode JSON from param
// For example, strings will be encoded so JavaScript reads them exactly
// as on Dart
args.write(json.encode(param));
args.write(',');
}

Expand All @@ -144,11 +147,6 @@ class HtmlUtils {
return function;
}

/// Adds single quotes to the param
static String addSingleQuotes(String data) {
return "'$data'";
}

/// Embeds js in the HTML source at the specified position
/// This is just a helper function for the generic [embedInHtmlSource] function
static String embedJsInHtmlSource(
Expand Down