【问题标题】:Trigger a function in an App via HTML / JS通过 HTML / JS 在 App 中触发函数
【发布时间】:2020-08-17 17:34:25
【问题描述】:

我想在不添加侧边菜单的情况下在我的网络应用中实现应用内购买。 我使用在 codecanyon 上找到的用于 Webapp 的 RocketWeb 应用程序模板。

是否可以在应用程序和网站上实现触发器来实现这一点:

用户按下 Button1 (HTML) 会触发 App 中的一个功能,会弹出一个 In-app Purchase Modal。 我想这样做是因为 Google 不太乐意添加直接付款。

Modals n Co 应该没问题,但我想知道是否可以将应用程序“桥接”到网站。

【问题讨论】:

    标签: javascript android html


    【解决方案1】:

    是的,有可能。你可以bridge Webview 到你的应用程序 - JS in WebView

    你需要做什么:

    1. 确保在您的 WebView 中启用了 JS
    WebView myWebView = (WebView) findViewById(R.id.webview);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    
    1. 创建JS监听接口,可以处理WebView发送的消息:
    public class WebAppInterface {
        Context mContext;
    
        /** Instantiate the interface and set the context */
        WebAppInterface(Context c) {
            mContext = c;
        }
    
        /** Show a toast from the web page */
        @JavascriptInterface
        public void openPurchaceModal(String toast) {
            //TODO open your purchase screen using mContext as your context
        }
    }
    

    警告:如果您将 targetSdkVersion 设置为 17 或更高,则必须将 @JavascriptInterface 注释添加到您希望 JavaScript 可用的任何方法,并且该方法必须是公共的。如果您不提供注释,则在 Android 4.2 或更高版本上运行时,您的网页无法访问该方法。

    1. 设置 WebView 的监听器:
    //Adds listener to the webView, under global JS object `Bridge` (You can use any name you want here)
    webView.addJavascriptInterface(new WebAppInterface(this), "Bridge");
    
    1. 在 WebView 内的 JS 中使用您的 Bridge 对象,无论您需要什么,就像这样:
     Bridge.openPurchaceModal();
    

    你可以在你的监听器中定义多个方法,并像这样调用它们:

    Bridge.[method name]();

    您还可以为这些方法添加原始参数,例如 String、int、boolean 等:

    ...
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
    ...
    

    并使用它:

    Bridge.showToast("toast text");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 2013-06-14
      • 2020-10-31
      • 1970-01-01
      相关资源
      最近更新 更多