Chrome 擴展機制

    聽說,今年9月份開始,谷歌將在Chrome瀏覽器中全面禁用NPAPI插件,Chrome 45之後將沒法再加載NPAPI插件,並推出了一種新的機制:擴展。html

    其實,若是把瀏覽器看做一塊畫布的話,NPAPI插件就像掛在畫布上的各類小飾品,而擴展更像拼接在畫布外小拼圖。不管是插件仍是擴展,都是爲了讓這副畫更符合用戶的指望。下面就只准備簡單介紹一下擴展和Native Message機制。chrome

    擴展安裝包json

    一個完整的擴展包,最終會一個.crx的壓縮文件包存在,使用zip的解壓文件能夠直接打開的。api

   擴展安裝,共有兩種方式:瀏覽器

   1)在Google APP Store中,找到相關的擴展,直接點擊添加app

   2)在Chrome瀏覽器的地址欄中,輸入chrome://extensions,打開擴展管理頁面;ide

        再將crx文件,直接拖進去就行了。post

    若是擴展沒法與瀏覽器搭上線,那麼擴展就真的一個塊剛好放在瀏覽器邊上的一塊小拼圖了。網站

    擴展與瀏覽器間的通訊,能夠有兩種形式:ui

    1)短鏈接    

        發送消息:chrome.runtime.sendMessage

        接收事件:chrome.runtime.onMessage.addListener

    2)長鏈接

         發送消息:var port = chrome.runtime.connect            

                       port.postMessage

        接收事件:port.onMessage.addListener

    在某些時候,只經過擴展沒法達到咱們預期的效果,這個時候就須要引入Host端。從瀏覽器看下來,就是:瀏覽器<----->擴展<------>Host端。就是說:瀏覽器與擴展能夠相互通訊,擴展與Host端能夠相互通訊,可是Host端與瀏覽器沒法直接通訊。Chrome的示例給出的Demo,也是這樣的一個結構。

    擴展與Host端的通訊,就須要聽從Native Message機制的。爲了實現Native Message機制通訊,須要提早作些準備:

    1)Host端、擴展

    2)Host端的JSON文件,在這個文件中定義了Host應用的名稱,併爲其綁定了擴展ID。只有在這裏綁定過的,纔是合法的,纔是能夠進行通訊。

    3)Host端的JSON文件,既然這麼重要,那麼瀏覽器要怎麼樣才能找到這個文件呢?

         Windows平臺下,是寫在了註冊表中;Mac下則是放在了指定目錄下。

         Windows平臺:HKEY_LOCAL_MACHINE\SOFTWARE\Google\Chrome\NativeMessagingHosts\com.my_company.my_application或

                              HKEY_CURRENT_USER\SOFTWARE\Google\Chrome\NativeMessagingHosts\com.my_company.my_application

         Mac平臺:/Library/Google/Chrome/NativeMessagingHosts/com.my_company.my_application.json 或

          ~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.my_company.my_application.json

    Native Message機制的通訊方式,也有兩種形式:

    1)短鏈接

        發送消息:chrome.runtime.sendNativeMessage

    2)常鏈接

        發送消息:var port = chrome.runtime.connectNative

                      port.postMessage

        接收事件:port.onMessage.addListener

                      port.onDisconnect.addListener

    關於Native Message機制,須要注意

    1)擴展與Host端的通訊,其實理解能夠爲基於標準輸入輸出接口的進程通訊。在Host端中,必須以二進制流的方式進行讀寫。

    2)從擴展到Host端的,單條消息最大不超過4GB

        從Host端到擴展的,單條消息最大不超過1MB

    3) 每條消息,都一個4字節的頭,用來表示消息的長度。

    Google的官方說明:

Chrome starts each native messaging host in a separate process and communicates with it using standard input ( stdin ) and standard output ( stdout ). The same format is used to send messages in both directions : each message is serialized using JSON, UTF-8 encoded and is preceded with 32-bit message length in native byte order .  The maximum size of a single message from the native messaging host is 1 MB , mainly to protect Chrome from misbehaving native applications.  The maximum size of the message sent to the native messaging host is 4 GB.

  

參考網址

NPAPI的介紹

https://zh.wikipedia.org/wiki/NPAPI

https://developer.chrome.com/extensions/npapi

某軟件給出的擴展安裝方式

http://honx.in/i/U7JbRYKo13vu6TsJ

中文文檔(比官方更新要慢些)

http://chrome.cenchy.com/index.html

http://open.chrome.360.cn/

相關文章
相關標籤/搜索