ios 跨域_如何在iOS和Android中建立跨域通信橋

ios 跨域

I was working on a certain project at work, in which I needed to connect several varying components via messages. Each had its own logic and code language. This made me want to understand all the ways different platforms enable communication.

我正在工作的某個項目上,需要通過消息連接幾個不同的組件。 每個都有自己的邏輯和代碼語言。 這使我想了解不同平臺實現通信的所有方式。

This article’s aim is to explain these cross-origin communication bridges and present simple, yet informative, examples to achieve them.

本文的目的是解釋這些跨域通信橋梁,并提供實現這些目標的簡單但有用的示例。

There will also be plenty of bridge puns ?

還會有很多雙關語嗎?

YOU WERE WARNED.

您被警告。

If you just want to get your hands dirty with the code, there are links to the GitHub repositories at the bottom of this article.

如果您只是想弄清楚代碼,可以在本文底部找到指向GitHub存儲庫的鏈接。

Typically, the JavaScript you write will run inside a browser. On iOS, it can either be a UIWebView or a WKWebView. On Android, a WebView.

通常,您編寫JavaScript將在瀏覽器中運行。 在iOS上 它可以是UIWebView或WKWebView。 在Android上 ,是WebView。

Since iOS can be the more exasperating of the platforms, I’ll describe the communication bridge there first.

由于iOS可能會使平臺更加惱人,因此我將首先在此描述通信橋。

倫敦橋倒塌(iOS) (London Bridge is Falling Down (iOS))

From iOS 8 onwards, Apple recommends using WKWebView instead of UIWebView, so the following will only address the bridge on a WKWebView.

從iOS 8開始,Apple建議使用WKWebView而不是UIWebView,因此以下內容僅解決WKWebView上的

For a UIWebView reference, please go here.

有關UIWebView的參考,請轉到此處 。

To send messages from the WKWebView to JavaScript, you use the method below:

要將消息從WKWebView發送到JavaScript,請使用以下方法:

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *error))completionHandler;

To receive messages from JavaScript inside your WKWebView, you must do the following:

要從WKWebView內部JavaScript接收消息,您必須執行以下操作:

  1. Create an instance of WKWebViewConfiguration

    創建WKWebViewConfiguration的實例

  2. Create an instance of WKUserContentController

    創建WKUserContentController的實例

  3. Add a script message handler to your configuration (this part bridges the gap). This action also registers your message handler on the window object under the following path: window.webkit.messageHandlers.MSG_HANDLER_NAME

    將腳本消息處理程序添加到您的配置中(這部分彌合了差距)。 此操作還將您的消息處理程序注冊到以下路徑下的window對象上: window.webkit.messageHandlers.MSG_HANDLER_NAME

  4. Make the class implement the message handler protocol by adding <WKScriptMessageHandler> at the top of the file

    通過在文件頂部添加<WKScriptMessageHandler>,使類實現消息處理程序協議。
  5. Implement userContentController:didReceiveScriptMessage (this method handles receiving the messages from JavaScript)

    實現userContentController:didReceiveScriptMessage (此方法處理從JavaScript接收消息)

建筑橋梁 (Building Bridges)

Let’s say we have the following HTML page set up:

假設我們設置了以下HTML頁面:

<html><head><title>Javascript-iOS Communication</title></head><body><script>window.webkit.messageHandlers.myOwnJSHandler.postMessage("Hello World!");</script></body></html>

And in our native code we implement the steps described above:

在我們的本機代碼中,我們實現了上述步驟:

#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>// 4
@interface ViewController : UIViewController <WKScriptMessageHandler>@property(nonatomic, strong) WKWebView *webview;

And violà! Now you have full JavaScript - iOS Communication!

和提琴! 現在,您已經擁有完整JavaScript-iOS通信!

過橋(Android) (Crossing The Bridge (Android))

Things are much simpler and more friendly here. In order to set up our communication bridge, there are only a few steps:

這里的事情更加簡單和友好。 為了建立我們的溝通橋梁,只有幾個步驟:

  1. Create an instance of a WebView object

    創建一個WebView對象的實例

  2. Enable JavaScript inside this WebView (setJavaScriptEnabled)

    在此WebView中啟用JavaScript( setJavaScriptEnabled )

  3. Set your own JavaScript Interface (which will hold methods that are visible to your JavaScript)

    設置自己JavaScript接口(將包含對JavaScript可見的方法)
  4. Any method that you want exposed to your JavaScript must have the @JavascriptInterface annotation before its declaration

    您想要公開給JavaScript的任何方法都必須具有@JavascriptInterface 注解 在宣布之前

Like before, let’s assume we have created this HTML file:

像以前一樣,假設我們已經創建了這個HTML文件:

And we have created the following simple Android Application:

我們創建了以下簡單的Android應用程序:

And there you go!

然后你去了!

You can now consider yourself a Native Communication Ninja!

您現在可以認為自己是本地交流忍者!

Here are the links to the repositories:

以下是存儲庫的鏈接:

AndroidtoJS RepositoryAndroidtoJS存儲庫 iOStoJS RepositoryiOStoJS存儲庫

iOS關于iOS的重要說明?? (?? Important Note Regarding iOS ??)

When you get to the point that you want to destroy your WKWebView, it is imperative that you remove your script message handler. If you do not do so, the script message handler will still hold a reference to your WKWebView and memory leaks will ensue upon creating new WKWebViews.

當您到達要銷毀WKWebView的地步時,它就是 勢在必行 您刪除腳本消息處理程序。 如果不這樣做,腳本消息處理程序將仍然保留對WKWebView的引用,并且在創建新的WKWebViews時將發生內存泄漏。

翻譯自: https://www.freecodecamp.org/news/how-to-build-cross-origin-communication-bridges-in-ios-and-andriod-7baef82b3f02/

ios 跨域

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393591.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393591.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393591.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

阿里巴巴旗下平臺口碑推出無人收銀技術,改造便利店市場;重慶法院運用 AI 探索“智能判案”...

阿里巴巴旗下平臺口碑推出無人收銀技術&#xff0c;改造便利店市場 雷鋒網消息 阿里巴巴旗下本地生活服務平臺口碑今日宣布在上海新興便利店品牌24鮮上線無人收銀技術。消費者只要打開支付寶&#xff0c;掃一掃想要購買的商品的條形碼&#xff0c;就可以自助提交訂單完成支付。…

如何使用射手影音尋找字幕

我們以"理智與情感"Sense and Sensibility為例&#xff0c;在迅雷搜索了下載&#xff0c;結果到了99%就不動了&#xff0c;由于是字幕文件&#xff0c;不能直接把TD的后綴去掉看影片&#xff0c;但是影片已經下載完成&#xff0c;所以我們使用射手影音播放該電影。&a…

mysql 表分區優缺點_Mysql分區表局限性總結

本文測試的版本XML/HTML代碼mysql>select version();------------| version() |------------| 5.1.33-log |------------1 row in set (0.00 sec)一、關于Partitioning Keys, Primary Keys, and UniqueKeys的限制在5.1中分區表對唯一約束有明確的規定&#xff0c;每一個唯一…

C# PagedList 真分頁

一&#xff1a;nuget 下載 PagedList 二&#xff1a;前端頁面 1.需要的數據 model PagedList.IPagedList<DeviceModel>  using PagedList.Mvc 2.使用數據 foreach (var item in Model)   {    <tr> <td>item.Name</td>       <td>…

leetcode1497. 檢查數組對是否可以被 k 整除

給你一個整數數組 arr 和一個整數 k &#xff0c;其中數組長度是偶數&#xff0c;值為 n 。 現在需要把數組恰好分成 n / 2 對&#xff0c;以使每對數字的和都能夠被 k 整除。 如果存在這樣的分法&#xff0c;請返回 True &#xff1b;否則&#xff0c;返回 False 。 示例 1…

計算機頁面設置代碼,計算機二級考試Access輔導:頁面設置模塊代碼分享

Dim up, dn, le, ri, si, liAs Single , co As string’定義邊距及頁面函數Sub ymszmk(strName As String) ’頁面設置模塊On Error GoTo Err_ymszmkIf Nz(DCount("*", "REPORTLIP", "REPORT’" & strName & "’")) 0 ThenMs…

讓我們了解Set及其在JavaScript中的獨特功能

by Asif Norzai通過Asif Norzai 讓我們了解Set及其在JavaScript中的獨特功能&#x1f3b2; (Lets learn about Set and its unique functionality in JavaScript &#x1f3b2;) 設置&#x1f3b2; (SET &#x1f3b2;) ES2015/ES6 gave us a lot of useful tools and feature…

C語言第二次博客作業---分支結構

一、PTA實驗作業 題目1&#xff1a;計算分段函數[2] 本題目要求計算下列分段函數f(x)的值&#xff1a; 1.實驗代碼 double x,result;scanf("%lf",&x);if(x>0){resultsqrt(x);}else{resultpow(x1,2)2*x1/x;}printf("f(%.2f) %.2f",x,result); 2 設計…

oracle+數據到+mysql數據庫亂碼_oracle數據mysql數據庫亂碼

{"moduleinfo":{"card_count":[{"count_phone":1,"count":1}],"search_count":[{"count_phone":4,"count":4}]},"card":[{"des":"阿里云數據庫專家保駕護航&#xff0c;為用戶…

ajax 不執行

1、get形式訪問&#xff1a; 一個相同的URL 只有一個結果&#xff0c;所以 第二次訪問的時候 如果 URL字符串沒變化 瀏覽器是 直接拿出了第一次訪問的結果&#xff0c;post則不會 解決辦法: 1、urlnew Date(); &#xff08;每次訪問時url不同&#xff09; 2、 type : get,   …

leetcode870. 優勢洗牌(貪心算法)

給定兩個大小相等的數組 A 和 B&#xff0c;A 相對于 B 的優勢可以用滿足 A[i] > B[i] 的索引 i 的數目來描述。 返回 A 的任意排列&#xff0c;使其相對于 B 的優勢最大化。 示例 1&#xff1a; 輸入&#xff1a;A [2,7,11,15], B [1,10,4,11] 輸出&#xff1a;[2,11,…

Mysql中行轉列和列轉行

一、行轉列即將原本同一列下多行的不同內容作為多個字段&#xff0c;輸出對應內容。建表語句DROP TABLE IF EXISTS tb_score; CREATE TABLE tb_score( id INT(11) NOT NULL auto_increment, userid VARCHAR(20) NOT NULL COMMENT 用戶id, subject VARCHAR(20) COMMENT…

OSChina 周四亂彈 ——妹子喜歡的是程序員 這是標準……

2019獨角獸企業重金招聘Python工程師標準>>> Osc亂彈歌單&#xff08;2017&#xff09;請戳&#xff08;這里&#xff09; 【今日歌曲】 一葉孤鴻 &#xff1a;分享Nanaka的單曲《いのちの名前&#xff08;Cover 木村弓&#xff09;》 《いのちの名前&#xff08;C…

阿里薪資談判技巧_如何像專業人士一樣處理技術職業中的薪資談判

阿里薪資談判技巧by Aline Lerner通過艾琳勒納(Aline Lerner) 如何像專業人士一樣處理技術職業中的薪資談判 (How to handle salary negotiations in your tech career like a pro) 確切地談薪水時要說些什么 (Know exactly what to say when negotiating your salary) There …

xp系統sql服務器怎么找,SQL文件在winxp系統下怎么打開

很多用戶不知道SQL文件是什么?SQL文件怎么打開?我們存儲數據時候經常會遇到SQL文件&#xff0c;如果你不知道WinXP系統SQL文件是什么以及怎么打開的話&#xff0c;那就趕緊看看小編整理的以下文章內容吧!SQL文件是什么?學習編程的同學可能都知道SQL是一種高級的非過程化的編…

Silverlight 設計器加載錯誤

每次打開silverlight頁面出如下錯誤 然后設計器不能將頁面加載出來 最后找了蠻多資料的 感覺這個原因有可能&#xff1a;“控制面板的添加刪除程序那里&#xff0c;選中Microsoft Silverlight&#xff0c;看看他的版本&#xff0c;是否與所裝的SDK的版本號一致。就算兩個版本號…

mysql索引優化實際例子_MySQL索引優化的實際案例分析

Order by desc/asc limit M是我在mysql sql優化中經常遇到的一種場景&#xff0c;其優化原理也非常的簡單&#xff0c;就是利用索引的有序性&#xff0c;優化器沿著索引的順序掃描&#xff0c;在掃描到符合條件的M行數據后&#xff0c;停止掃描&#xff1b;看起來非常的簡單&am…

leetcode441. 排列硬幣(二分查找)

你總共有 n 枚硬幣&#xff0c;你需要將它們擺成一個階梯形狀&#xff0c;第 k 行就必須正好有 k 枚硬幣。 給定一個數字 n&#xff0c;找出可形成完整階梯行的總行數。 n 是一個非負整數&#xff0c;并且在32位有符號整型的范圍內。 示例 1: n 5 硬幣可排列成以下幾行: …

【洛谷 P2051】 [AHOI2009]中國象棋(DP)

題目鏈接 首先想到狀壓dp&#xff0c;但是\(n,m\)高達100&#xff0c;怎么壓&#xff1f; 容易發現&#xff0c;每行每列最多兩個象棋&#xff0c;否則就直接gg了。 一個巧妙的設置狀態的方式是&#xff0c;只需要記錄到當前行有多少列是放了1個炮和2個炮。 然后每一行有3種選擇…

循環 直到 python_如果您在Python中存在慢循環,則可以對其進行修復……直到無法解決為止...

循環 直到 pythonby Maxim Mamaev馬克西姆馬馬耶夫(Maxim Mamaev) Let’s take a computational problem as an example, write some code, and see how we can improve the running time. Here we go.讓我們以一個計算問題為例&#xff0c;編寫一些代碼&#xff0c;看看如何改…