欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

js与ios交互,使用WebViewJavascriptBridge

程序员文章站 2022-04-12 20:28:55
js与ios交互,使用webviewjavascriptbridge。
   

js与ios交互,使用webviewjavascriptbridge。

<pre class="brush:java;">   <button>点我</button>
    <input value="" id="res" type="text"></pre><p></p>
<pre class="brush:java;"></pre>
<strong>js端:</strong><br>
<br>
<p></p>
<p>1,固定代码放js里:</p>
<p></p><pre class="brush:java;">        function setupwebviewjavascriptbridge(callback){
        if (window.webviewjavascriptbridge) { return callback(webviewjavascriptbridge); }
        if (window.wvjbcallbacks) { return window.wvjbcallbacks.push(callback); }
        window.wvjbcallbacks = [callback];
        var wvjbiframe = document.createelement('iframe');
        wvjbiframe.style.display = 'none';
        wvjbiframe.src = 'wvjbscheme://__bridge_loaded__';
        document.documentelement.appendchild(wvjbiframe);
        settimeout(function() { document.documentelement.removechild(wvjbiframe) }, 0)
        }</pre><br>
<br>
2,封成函数方便后面交互时调用:<pre class="brush:java;">nativeinteractive=function(fn,obj){
    setupwebviewjavascriptbridge(function(bridge) {
             if(obj){
                  bridge.callhandler('webview_call_native', obj, function(response) {});
             }
             bridge.registerhandler('native_call_webview', function(data,response) {
                  fn(data);
             })
        }); 
   }</pre><pre class="brush:java;"><pre class="brush:java;">native_call_webview是要接受ios端参数的函数名;<pre class="brush:java;">webview_call_native是要传参给ios的参数名;</pre><p></p>
<pre class="brush:java;"></pre>
这两个名字要与ios端协商好;
<pre class="brush:java;"></pre>
3,调用:
<p></p>
<p></p><pre class="brush:java;">$("button").click(function(){
        var native=function(data){//ios向js传参是data
            if(data.say=="yes"){
                $("#res").val(data.iossay);
            }
            responsecallback({'jssay': 'yes'});//回复ios
        }
         var requesth5={//向ios传参
            user_id:"js001",
                    jssay:"can you hear me?"   
                 }
        nativeinteractive(native,requesth5);
    })</pre><br>
<br>
<p></p>
<p><br>
</p>
    
<p></p>                     </pre></pre>