title: In Chrome Native messaging: how long is the native app instance object lifetime?
body: <p>Does a native application that talks to a Chrome extension is alive for ever? I mean should it be present e.g. before a postback happens? I could not find any configuration for that to add in the manifest file.</p>
  
  <p>I have a page, there are some objects on the page. After clicking an object and sending/receving one message with the Native app, then it no longer works for the rest of objects. </p>
  
  <p><strong>My exact question</strong>: How long is the native app instance object lifetime? Should that object response e.g. forever? Or do I need a loop e.g. to read messages from stdin if this is a continuous communication?</p>
  
  <p><strong>Here is my background script:</strong></p>
  
  <pre><code>var host_name = "files.mffta.java.nativeapp";
  var port = null;
  initPort();
  function initPort() {
      console.log( 'Connecting to native host: ' + host_name );
      port = chrome.runtime.connectNative( host_name );
      port.onMessage.addListener( onNativeMessage );
      port.onDisconnect.addListener( onDisconnected );
  }
  
  // Listen for messages that come from the content script.
  chrome.runtime.onMessage.addListener(
    function( messageData, sender, sendResponse ) {
      if( messageData ) {
          sendNativeMessage(messageData);
          sendResponse( { res: 'done!' } );
      }
    } );
  
  // Sending a message to the port.
  function sendNativeMessage(messageData) {
      if( port == null )
          initPort();
      console.log( 'Sending message to native app: ' + JSON.stringify( messageData ) );
      port.postMessage( messageData );
      console.log( 'Sent message to native app.' );
  }
  
  // Receiving a message back from the Native Client API.
  function onNativeMessage( message ) {
      console.log( 'recieved message from native app: ' + JSON.stringify( message ) );
  
      alert( "messaged received from Native: " + JSON.stringify( message ) );
      //sending a message to Content Script to call a function
      if( message.methodName &amp;&amp; message.methodName != "" ) {
          chrome.tabs.query( { active: true, currentWindow: true }, function( tabs ) {
              chrome.tabs.sendMessage( tabs[0].id, message, function( response ) {
                  // Call native again to return JavaScript callback function results
                  alert ("calc res received by extension : " + response);
                  sendNativeMessage({ type: "JSCallbackRes", callbackRes: response });
              } );
          } );
      }
  }
  
  // Disconnecting the port.
  function onDisconnected() {
      console.log( "ERROR: " + JSON.stringify( chrome.runtime.lastError ) );
      console.log( 'disconnected from native app.' );
      port = null;
  }
  </code></pre>
  
  <p><strong>My extension manifest:</strong></p>
  
  <pre><code>{
    "name": "Files.ChromeExt.Operarations",
    "version": "1.0",
    "manifest_version": 2,
    "description": "This extension calls a Native API which that API calls some x-Files related operations.",
    "icons": {
      "128": "x-files_icon.png"
    },
    "permissions": [
      "nativeMessaging", "activeTab"
    ],
    "background": {
      "persistent": true,
      "scripts": ["main.js"]
    },
    "content_scripts" : [{"matches": ["http://localhost/*","https://localhost/*"], 
      "js": ["contentscripts/page.js"]}]
  } 
  </code></pre>
  
  <p><strong>Java program:</strong> [as has been asked in the comments]</p>
  
  <pre><code>import java.io.IOException;
  import javax.swing.JOptionPane;
  
  public class Applet {
  
      public Applet(){}
  
      public static void main(String[] args) {
          try {
              readMessage();
              sendMessage("{\"msg\" : \"hello\"}");
  
          } catch (Exception ex) {
              JOptionPane.showMessageDialog(null, ex.getMessage());
          }
      }
  
      public static String readMessage() {
          String msg = "";
          try {
              int c, t = 0;
              for (int i = 0; i &lt;= 3; i++) {
                  t += Math.pow(256.0f, i) * System.in.read();
              }
  
              for (int i = 0; i &lt; t; i++) {
                  c = System.in.read();
                  msg += (char) c;
              }
          } catch (Exception e) {
              JOptionPane.showMessageDialog(null, "error in reading message from JS");
          }
          return msg;
      }
  
      public static void sendMessage(String msgdata) {
          try {
              int dataLength = msgdata.length();
              System.out.write((byte) (dataLength &amp; 0xFF));
              System.out.write((byte) ((dataLength &gt;&gt; 8) &amp; 0xFF));
              System.out.write((byte) ((dataLength &gt;&gt; 16) &amp; 0xFF));
              System.out.write((byte) ((dataLength &gt;&gt; 24) &amp; 0xFF));
  
              // Writing the message itself
              System.out.write(msgdata.getBytes());
              System.out.flush();
          } catch (IOException e) {
              JOptionPane.showMessageDialog(null, "error in sending message to JS");
          }
      }
  }
  </code></pre>
  
  <p>By inspecting the chrome log I can see these messages:</p>
  
  <ul>
  <li><em>Native Messaging host tried sending a message that is 1936028240 bytes long.</em></li>
  <li><em>{"message":"Error when communicating with the native messaging host."}", source: chrome-extension://XXX</em></li>
  </ul>
  
  <p>I am testing these on a Win 8.0 machine 64 bit.</p>
  
  <p><strong>Update:</strong>
  I am now convinced that the host is alive forever if connectNative is called and the port is not stopped by an error. So, the root cause of the error messages above must be something else than port lifetime. I mean some error in my communication is forcibly stopping the port.</p>
  
  <p>I highly appreciate any comments you can give.</p>