Google Chrome Native Messaging开发实录(二)Chrome Extension扩展
接上一篇《Google Chrome Native Messaging开发实录(一)背景介绍》的项目背景,话不多说,有关Chrome Extension介绍和文档就不展开了,直接上代码。
首先准备一个测试效果的页面demo.html
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>Printer Demo</title> </head> <html> <body> <input id="cardno" type="text" /> <input id="mybutton" type="button" value="打卡" /> </body> </html>
chrome extension部分,manifest.json
{ "name": "My Printer", "version": "1.0.0", "manifest_version": 2, "content_scripts": [ { "matches": ["http://localhost:5103/*"], "js": ["contentscript.js"] } ], "background": { "scripts": ["background.js"] }, "permissions": [ "nativeMessaging" ] }
contentscript.js
var button = document.getElementById("mybutton"); var cardno = document.getElementById("cardno"); button.addEventListener("click", function () { chrome.extension.sendMessage("some message", function (response) { //alert(response); }); }, false); chrome.runtime.onMessage.addListener(function (data) { alert(data.cardno); cardno.value = data.cardno; });
background.js
var host_name = "com.my.printer"; var port = null; var tab = null; function connectToNative() { console.log('Connecting to native host: ' + host_name); port = chrome.runtime.connectNative(host_name); port.onMessage.addListener(onNativeMessage); port.onDisconnect.addListener(onDisconnected); } function sendNativeMessage(msg) { message = { "text": msg }; console.log('Sending message to native app: ' + JSON.stringify(message)); port.postMessage(message); console.log('Sent message to native app: ' + msg); } function onNativeMessage(message) { console.log('recieved message from native app: ' + JSON.stringify(message)); chrome.tabs.sendMessage(tab, message); } function onDisconnected() { //console.log(chrome.runtime.lastError); console.log('disconnected from native app.'); port = null; res = null; } chrome.extension.onMessage.addListener(function (data, sender, response) { tab = sender.tab.id; connectToNative(); sendNativeMessage(data); return true; });
针对代码细节,提请大家必须要注意的有:
1.native messaging相关api在chrome.runtime包中,只能在background中调用(可以是html或script)。
2.content script虽然不能直接调用native messaging api,但需要它起到中转消息改变页面元素的作用。chrome.extension.sendRequest方法已过期,它向background传递消息使用chrome.runtime.sendMessage替代。
3.在background中监听来自tab的消息chrome.extension.onRequest在官方文档中建议是用chrome.runtime.onMessage替代,但其实可以用chrome.extension.onMessage的,截止到写本文时官方的chrome extension api列表中并没有给出这样的写法,不要怀疑它的可用性。