background

I have been using FLUTTER for mixed development, and now I plan to use the common ability of flutter multi-platform code to do multi-platform development. Therefore, I have done preliminary research. Since JS interaction is done by WebViewBridge in mobile terminal project, the interaction ability of Flutter Web is verified

research

The dart call js

Flutter provides the dart:js package, which can be used to interact with JS. The official documentation of flutter cannot be packaged as an APP if import ‘dart:js’ is called in the project.

Take the example of calling JS alert

js.context.callMethod("alert", [content]);
Copy the code

The first argument is the name of the js method, followed by the argument to the method, which will make alert pop up

The dart call WebviewBridge

So now that we know how to call JS, we still can’t call WebviewBridge, because WebviewBridge and native interaction need to add a JS method, so we need to write a bridge file, complete the method registration, so we can call WebviewBridge

function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } window.WVJBCallbacks = [callback]; // Create an array of WVJBCallbacks global properties and insert callback into the array. var WVJBIframe = document.createElement('iframe'); // Create an iframe element wvjbiframe.style. display = 'none'; // Wvjbifame. SRC = 'https://__BRIDGE_LOADED__'; / / set the iframe SRC attribute document. The documentElement. The appendChild (WVJBIframe); // Add iframe to the current text navigation. setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0) } function webviewBridge(fun,data) { setupWebViewJavascriptBridge(function(bridge){ if ( window.WebViewJavascriptBridge) { window.WebViewJavascriptBridge.callHandler(fun,{'data':data}); }}); } function webviewCallBackBridge(fun,callback,data) { setupWebViewJavascriptBridge(function(bridge){ if ( window.WebViewJavascriptBridge) { window.WebViewJavascriptBridge.callHandler(fun,{'data':data},callback); }}); } window.setupWebViewJavascriptBridge = setupWebViewJavascriptBridge; window.webviewBridge = webviewBridge; window.webviewCallBackBridge = webviewCallBackBridge;Copy the code

Reference the JS file in index.html so that DART can call the encapsulated method. (Try not to use ES6 syntax in JS. During the test, an Android phone with a low kernel version did not support ES6, so it could not be called successfully.)

The specific implementation

The implementation can be seen in code: Git code

I wrote a code implementation, mainly realizing dart call JS, DART call native, DART call native return data, dart call native, check cookie