How to Call Native Iphone/Android function from Javascript?

后端 未结 2 1163
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 21:54

I am using Web View both in Iphone and Android. In Android, I use create a variable to call native Andriod functions/methods. But I have not able to find something similar i

相关标签:
2条回答
  • 2020-12-28 22:19

    iOS

    In iOS you could use a custom url scheme by implementing shouldStartLoadWithRequest. If I would by example want to change the toolbar's tint color:

    ViewController.h

    @property (strong, nonatomic) IBOutlet UIToolbar *toolbar;
    

    ViewController.m

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        NSURL *url = request.URL;
        NSString *scheme = [url scheme];
    
        if ([scheme isEqualToString:@"color"]) {
            self.toolbar.tintColor = [self colorWithHexString:url.host];
        }
    
        return YES;
    }
    

    Javascript

    In javascript you just change window.location, which will launch a fire and forget:

    window.location = 'color://' + color;
    

    Just chain your parameters like:

    window.location = 'myscheme://param1/' + value1 + '/param2/' + value2;
    

    Just make sure you use encodeURIComponent to encode your parameters (to create a valid url).

    More info

    Android

    In Android you add a javascript interface:

        WebView webView = getWebView();
        webView.loadUrl("http://localhost:8080");
        // must be after loadUrl on lower apis
        webView.addJavascriptInterface(new AndroidBridge(this), "AndroidBridge");
    

    ...

    public class AndroidBridge {
    
        private MainActivity activity;
    
        public AndroidBridge(MainActivity activity) {
            this.activity = activity;
        }
    
        @JavascriptInterface
        public void changeNavbarBackground(String color) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
            Log.i(getClass().getSimpleName(), "changeNavbarBackground " + color);
    
            Field f = R.color.class.getField(color);
            final int col = (Integer) f.get(null);
    
            activity.changeNavbarBackground(col);
        }
    }
    

    Javascript

    In javascript you use the javascript interface:

    if (window.AndroidBridge) {
                window.AndroidBridge.changeNavbarBackground(color);
    }
    
    0 讨论(0)
  • 2020-12-28 22:39

    Firebase analytics sample for webview will give more insights to implement this feature. Please check on this sample

    For testing you can host the sample webpart on some server and load that url on webview.

    0 讨论(0)
提交回复
热议问题