JS與Native互動

來源:互聯網
上載者:User

JS與Native互動

實現JS和Native有兩種方式:

shouldOverrideUrlLoading(WebView view, String url) js與java互相調用

先來說一下第一種方式shouldOverrideUrlLoading(WebView view, String url)

通過給WebView加一個事件監聽對象(WebViewClient)並重寫shouldOverrideUrlLoading(WebView view, String url)方法。當按下某個串連時WebViewClient會調用這個方法,並傳遞參數view和url

開始第二種.JS和Java互調

如何?java和js互調

WebView開啟JavaScript指令碼執行 WebView設定供JavaScript調用的互動介面用戶端和網頁端編寫調用對方的代碼

JS調用JAVA
JS : window.jsInterfaceName.methodName(parameterValues)
native: webView.addJavascriptInterface(new JsInteration(), “androidNative”);

下面給出一個執行個體,方便理解

webView.addJavascriptInterface(new JsInteration(), “androidNative”);@JavascriptInterfacepublic void helloJS(){…}
window.androidNative.helloJS();

Java調用JS

webView調用js的基本格式為webView.loadUrl(“javascript:methodName(parameterValues)”)

調用js無參無傳回值函數: String call =“javascript:sayHello()”;webView.loadUrl(call); 調用js有參無傳回值函數:String call = “javascript:alertMessage(\”” + “content” + “\”)”; webView.loadUrl(call); 調用js有參數有傳回值的函數
Android在4.4之前並沒有提供直接調用js函數並擷取值的方法,所以在此之前,常用的思路是 java調用js方法,js方法執行完畢,再次調用java代碼將值返回。
Android 4.4之後使用evaluateJavascript即可。
private void testEvaluateJavascript(WebView webView) {  webView.evaluateJavascript("getGreetings()", new ValueCallback() {  @Override  public void onReceiveValue(String value) {      Log.i(LOGTAG, "onReceiveValue value=" + value);  }});}

注:

參數類型如果是簡單的int或String,可以直接傳,對於複雜的資料類型,建議以字串形式的json返回。 evaluateJavascript方法必須在UI線程(主線程)調用,因此onReceiveValue也執行在主線程。

當native與js互動時存cookie看到很多人遇到過這樣一個問題,cookie存不進去,網上有很多解釋方案,但是很多沒說到重點上,這裡直接貼一下代碼:

public static void synCookies(Context context, String url, String version) {        CookieSyncManager.createInstance(context);        CookieManager cookieManager = CookieManager.getInstance();        cookieManager.setAcceptCookie(true);        cookieManager.removeAllCookie();        cookieManager.setCookie(url, "sessionKey=" + UserInfoShareprefrence.getInstance(context).getLocalSessionKey());        cookieManager.setCookie(url, "productVersion=android-epocket-v" + version);        CookieSyncManager.getInstance().sync();    }

存不進去的很大一部分原因是你的url不對,他官方給出的解釋是這樣的

 /**     * Sets a cookie for the given URL. Any existing cookie with the same host,     * path and name will be replaced with the new cookie. The cookie being set     * will be ignored if it is expired.     *     * @param url the URL for which the cookie is to be set     * @param value the cookie as a string, using the format of the 'Set-Cookie'     *              HTTP response header     */    public void setCookie(String url, String value) {        throw new MustOverrideException();    }

其實沒說明白url到底是什麼,這裡的url就是顯示的url的網域名稱,這裡順便貼出取網域名稱的方法,給出的是通過正則提取網域名稱

    /**     * 獲得網域名稱     *     * @param url     * @return     */    public static String getDomain(String url) {        Pattern p = Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);        Matcher matcher = p.matcher(url);        matcher.find();        return matcher.group();    }

還有一點就是,如果你想傳遞多個值給cookie的話,可以多次使用setCookie,不要擅自的自己拼值,因為你拼的字串中可能存在分號,內部多分號做了特殊處理,截取分號之前的,之後的直接放棄!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.