Skip to main content

method channel JavaScript flutter

 method channel JavaScript  flutter 

 flutter plugin :  https://pub.dev/packages/webview_flutter

Step 1 - HTML CODE 

<!DOCTYPE html>
<html>
<head>
  <title>Thanks for your order!</title>
  <link rel="stylesheet" href="css/style.css">
  <script src="js/client.js" defer></script>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

</body>
<script type='text/javascript'>

function postMessage(){
  var data = {
        message: "Response from web",
        sender: "user123",
        timestamp: new Date().toISOString()
    };

    var jsonData = JSON.stringify(data);

    setTimeout(function() {
        PayResponse.postMessage(jsonData);
    }, 1500); // Delay of 1500 milliseconds (1.5 seconds)
}

window.onload = postMessage;

</script>
</html>

Step 2 - Flutter code 

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class FlutterWebView extends StatefulWidget {
const FlutterWebView({Key? key}) : super(key: key);

@override
State<FlutterWebView> createState() => _FlutterWebViewState();
}

class _FlutterWebViewState extends State<FlutterWebView> {
late WebViewController webViewController;

@override
void initState() {
// TODO: implement initState
super.initState();
webViewController = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {
// Update loading bar.
},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
onHttpError: (HttpResponseError error) {},
onWebResourceError: (WebResourceError error) {},
onNavigationRequest: (NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
),
)
..loadRequest(Uri.parse(''))
..addJavaScriptChannel("PayResponse", onMessageReceived: (var message) {
print("------message received------");
print(message.message);
Navigator.of(context).pop(message.message);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
body: WebViewWidget(
controller: webViewController,
));
}
}




Comments

Popular posts from this blog

Referral & Deep linking

  Plugins :  app_links: android_play_install_referrer: Link to share :  https://play.google.com/store/apps/details?id=com.erer&referrer=referral_code%3DTEST123 Flutter Code :  import 'package:app_links/app_links.dart' ; import 'package:android_play_install_referrer/android_play_install_referrer.dart' ; import 'package:flutter/foundation.dart' ; import 'package:shared_preferences/shared_preferences.dart' ; class DeepLinkService {   static const String _referralKey = 'referral_code' ;   static final AppLinks _appLinks = AppLinks ();   static Future < void > initDeepLinks () async {     debugPrint ( 'Initializing deep links...' );     // 1️⃣ Handle real-time deep/link stream     try {       final Uri ? initialUri = await _appLinks . getInitialAppLink ();       if ( initialUri != null ) {         debugPrint ( 'Initial deep link: $initialUri'...

API security best practices

 API with a focus on security best practices : Key Security Practices Included: Input Validation and Sanitization : All inputs are validated and sanitized to prevent SQL injection and other attacks. Prepared Statements : All database queries use prepared statements to avoid SQL injection. Password Hashing : Passwords are hashed using password_hash() and verified using password_verify() . Token-Based Authentication : JSON Web Tokens (JWTs) are used for secure API authentication. Error Hiding : Error details are logged but not exposed to users in production. Strict Content-Type Header : Ensures only JSON payloads are processed. Rate Limiting and Throttling : Optional mechanisms to prevent abuse. Validation for IDs : Integer inputs (like user_id or exam_id ) are explicitly validated.

Native api call flutter in terminated state

Calling Native Android Code from Flutter (Step-by-Step for Beginners) When you need to run platform-specific features (like background services, Bluetooth, or sensors) that Flutter doesn’t handle out of the box, you can use MethodChannels to talk to native Android or iOS code. In this tutorial, we’ll: Create a MethodChannel in Flutter. Set up a foreground service in Android. Trigger that service from Flutter—even when the app is closed. 1. What Is a MethodChannel? Think of a MethodChannel as a telephone line between Flutter (Dart) and the platform’s native code (Java/Kotlin for Android, Swift/Objective-C for iOS). Flutter side: “📞 Hey Android, please start the service!” Android side: “✅ Got it, I’m starting it now.” 2. Create the Channel in Flutter Create a new file: lib/native_service.dart import 'package:flutter/services.dart' ; class NativeService {   // ✅ A generic channel name you can reuse in any project   static const _channel = MethodChanne...