1 // Copyright 2013 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 var port = null; 6 7 var getKeys = function(obj){ 8 var keys = []; 9 for(var key in obj){ 10 keys.push(key); 11 } 12 return keys; 13 } 14 15 16 function appendMessage(text) { 17 document.getElementById('response').innerHTML += "<p>" + text + "</p>"; 18 } 19 20 function updateUiState() { 21 if (port) { 22 document.getElementById('connect-button').style.display = 'none'; 23 document.getElementById('input-text').style.display = 'block'; 24 document.getElementById('send-message-button').style.display = 'block'; 25 } else { 26 document.getElementById('connect-button').style.display = 'block'; 27 document.getElementById('input-text').style.display = 'none'; 28 document.getElementById('send-message-button').style.display = 'none'; 29 } 30 } 31 32 function sendNativeMessage() { 33 message = {"text": document.getElementById('input-text').value}; 34 port.postMessage(message); 35 appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>"); 36 } 37 38 function onNativeMessage(message) { 39 appendMessage("Received message: <b>" + JSON.stringify(message) + "</b>"); 40 } 41 42 function onDisconnected() { 43 appendMessage("Failed to connect: " + chrome.runtime.lastError.message); 44 port = null; 45 updateUiState(); 46 } 47 48 function connect() { 49 var hostName = "com.google.chrome.example.echo"; 50 appendMessage("Connecting to native messaging host <b>" + hostName + "</b>") 51 port = chrome.runtime.connectNative(hostName); 52 port.onMessage.addListener(onNativeMessage); 53 port.onDisconnect.addListener(onDisconnected); 54 updateUiState(); 55 } 56 57 document.addEventListener('DOMContentLoaded', function () { 58 document.getElementById('connect-button').addEventListener( 59 'click', connect); 60 document.getElementById('send-message-button').addEventListener( 61 'click', sendNativeMessage); 62 updateUiState(); 63 }); 64