“Führen Sie den nativen Betrieb mit JavaScript in Android durch” Code-Antworten

Führen Sie den nativen Betrieb mit JavaScript in Android durch

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

//HTML Content
/*
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web View Script</title>
</head>
<body>
<button id="success">Simulate Success</button>
<button id="failed">Simulate Failed</button>
<button id="sample">Simulate Sample Event</button>
<script>
    var success = document.getElementById('success');
    var failed = document.getElementById('failed');
    var sample = document.getElementById('sample');
    success.addEventListener('click', function () {
      var message = {
        "Status": "SUCCESS",
        "transactionId": "#PAY123133"
      };
      paymentResponse.postMessage(JSON.stringify(message));
    });
    failed.addEventListener('click', function () {
      var message = {
        "Status": "FAILED",
        "transactionId": "#PAY123133"
      };
      paymentResponse.postMessage(JSON.stringify(message));
    });
    sample.addEventListener('click', function () {
      var message = {
        "Status": "FAILED",
        "transactionId": "#PAY123133"
      };
      sampleMessage.postMessage(JSON.stringify(message));
    });
  </script>
</body>
</html>
*/
public class WebViewActivity extends AppCompatActivity {
    public static final String INTENT_EXTRA_URL = "INTENT_EXTRA_URL";
    private static final String TAG = "WebViewActivity";
    private final Handler myHandler = new Handler();


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        WebView paymentWebView = findViewById(R.id.paymentWebView);

        JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(this);

        paymentWebView.getSettings().setLightTouchEnabled(true);
        paymentWebView.getSettings().setJavaScriptEnabled(true);
        paymentWebView.addJavascriptInterface(myJavaScriptInterface, "paymentResponse");
        paymentWebView.addJavascriptInterface(myJavaScriptInterface, "sampleMessage");


        paymentWebView.setWebViewClient(new WebViewClient() {

            //If you will not use this method url links are opeen in new brower not in webview
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            //Show loader on url load
            public void onLoadResource(final WebView view, String url) {
                // TODO: 01/04/21 Show Waiting Indicator
            }

            public void onPageFinished(WebView view, String url) {
                // TODO: 01/04/21 Hide Waiting Indicator
            }

        });


        // TODO: 01/04/21 Change URL Base on your requirement
        String url = "file:///android_asset/index.html";
        paymentWebView.loadUrl(url);

    }

    private void showAlert(String title, String message) {
        AlertDialog alertDialog = new AlertDialog.Builder(WebViewActivity.this).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                (dialog, which) -> dialog.dismiss());
        alertDialog.show();
    }

    public class JavaScriptInterface {
        Context mContext;

        JavaScriptInterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void postMessage(String webMessage) {
            myHandler.post(() -> {
                try {
                    Log.d(TAG, "postMessage: " + webMessage);
                    JSONObject obj = new JSONObject(webMessage);
                    String status = obj.getString("Status");

                    switch (status) {
                        case "FAILED":

                            showAlert("Payment Declined", "Please try again");

                            break;

                        case "SUCCESS":
                            showAlert("Payment Success", obj.getString("transactionId"));
                            break;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            });

        }
    }
}
Developer101

"Native Operation von JavaScript in Android durchführen"

//
//  WebViewScriptViewController.swift
//  UpgradeMySelf-ios
//
//  Created by Shubham Sharma on 20/01/20.
//  Copyright © 2020 Shubham Sharma. All rights reserved.
//

import UIKit
import WebKit

/// -Html code:
/// -Message need to send
/// var message = {"Status": "SUCCESS", "transactionId": "#PAY123133" };
/// -send messge to webview
/// window.webkit.messageHandlers.paymentResponse.postMessage(message)

let htmlData = """
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Web View Script</title>
</head>

<body>

  <button id="success">Success</button>
  <button id="failed">Failed</button>
  <button id="sample">Sample</button>

  <script>
    var success = document.getElementById('success');
    var failed = document.getElementById('failed');
    var sample = document.getElementById('sample');

    success.addEventListener('click', function () {
      var message = {
        "Status": "SUCCESS",
        "transactionId": "#PAY123133"
      };
      window.webkit.messageHandlers.paymentResponse.postMessage(message)
    });

    failed.addEventListener('click', function () {
      var message = {
        "Status": "FAILED",
        "transactionId": "#PAY123133"
      };
      window.webkit.messageHandlers.paymentResponse.postMessage(message)
    });
    sample.addEventListener('click', function () {
      var message = {
        "Status": "FAILED",
        "transactionId": "#PAY123133"
      };
      window.webkit.messageHandlers.sample.postMessage(message)
    });
  </script>

</body>

</html>
"""



class WebViewScriptViewController: UIViewController, WKNavigationDelegate {
    
    @IBOutlet weak var webView: WKWebView!
    private var webViewContentIsLoaded = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ///register function name like paymentResponse or sample
        webView.configuration.userContentController.add(self, name: "paymentResponse")
        webView.configuration.userContentController.add(self, name: "sample")
        
        webView.scrollView.bounces = false
        webView.navigationDelegate = self
        
        if !webViewContentIsLoaded {
            if let url = Bundle.main.url(forResource: "index", withExtension: "html") { ///load html from local
                let request = URLRequest(url: url)
                webView.load(request)
            } else {
                webView.loadHTMLString(htmlData, baseURL: nil)
            }
            webViewContentIsLoaded = true
        }
    }
    
    
    func showAlertWithMessage(title: String, message:String ) {
        let alert = UIAlertController.init(title: title , message:message , preferredStyle:.alert)
        let action = UIAlertAction.init(title: "OK", style: .cancel) { (action) in
            
        }
        alert.addAction(action)
        self.present(alert, animated:true, completion: nil)
    }
}

extension WebViewScriptViewController: WKScriptMessageHandler {
    // MARK: - WKScriptMessageHandler
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.body)
        
        guard let body = message.body as? [String: Any] else {
            print("could not convert message body to dictionary: \(message.body)")
            showAlertWithMessage(title: "Payment Declined", message: "" )
            return
        }
        
        guard let status = body["Status"] as? String else {
            print("could not convert Status to string: \(body)")
            showAlertWithMessage(title: "Payment Declined", message: "" )
            return
        }
        
        switch status {
        case "FAILED":
            showAlertWithMessage(title: "Payment Declined", message: "")
            print("Transaction Failed")
            break
            
        case "SUCCESS":
            guard let transactionId = body["transactionId"] as? String else {
                print("could not transactionId to string: \(body)")
                return
            }
            print("outerHTML is \(transactionId)")
            showAlertWithMessage(title: "Payment Success", message: "Transaction Id \(transactionId)" )
            break
        default:
            print("unknown message type \(status)")
            return
        }
    }
}
Developer101

Ähnliche Antworten wie “Führen Sie den nativen Betrieb mit JavaScript in Android durch”

Fragen ähnlich wie “Führen Sie den nativen Betrieb mit JavaScript in Android durch”

Weitere verwandte Antworten zu “Führen Sie den nativen Betrieb mit JavaScript in Android durch” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen