8

Sto cercando di manipolare la pagina di contenuto che è attualmente nella scheda in Chrome e se non riesco a farlo in seguito, ho bisogno di trovare la strada per Fai quello!Chrome Native Messaging API chrome.runtime.connectNative non è una funzione

Ciao a tutti Sto cercando di ottenere questa nuova estensione di cromo che funziona con il mio programma C# per passare i messaggi avanti e indietro. Ho visto un sacco di demo di codice su StackOverflow e questo è principalmente ciò che sto passando, ma sembra che tutti gli esempi non stiano lavorando alla mia fine.

Il problema che sto avendo è che sto ottenendo l'errore di:

Connecting to native messaging host com.google.chrome.example.echo 
Uncaught TypeError: chrome.runtime.connectNative is not a function 

enter image description here

Ogni volta che provo a "collegarsi" alla porta.

Non so cosa sto facendo male da quando ho seguito altre tetorials qui e tutti sembrano affermare funziona ....

I main.js JS:

var port = null; 
var getKeys = function (obj) { 
    var keys = []; 
    for (var key in obj) { 
     keys.push(key); 
    } 
    return keys; 
} 
function appendMessage(text) { 
    document.getElementById('response').innerHTML += "<p>" + text + "</p>"; 
} 
function updateUiState() { 
    if (port) { 
     document.getElementById('connect-button').style.display = 'none'; 
     document.getElementById('input-text').style.display = 'block'; 
     document.getElementById('send-message-button').style.display = 'block'; 
    } else { 
     document.getElementById('connect-button').style.display = 'block'; 
     document.getElementById('input-text').style.display = 'none'; 
     document.getElementById('send-message-button').style.display = 'none'; 
    } 
} 
function sendNativeMessage() { 
    message = { "text": document.getElementById('input-text').value }; 
    port.postMessage(message); 
    appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>"); 
} 
function onNativeMessage(message) { 
    appendMessage("Received message: <b>" + JSON.stringify(message) + "</b>"); 
} 
function onDisconnected() { 
    appendMessage("Failed to connect: " + chrome.runtime.lastError.message); 
    port = null; 
    updateUiState(); 
} 
function connect() { 
    var hostName = "com.google.chrome.example.echo"; 
    appendMessage("Connecting to native messaging host <b>" + hostName + "</b>") 
    console.log("Connecting to native messaging host " + hostName); 
    port = chrome.runtime.connectNative(hostName); 
    port.onMessage.addListener(onNativeMessage); 
    port.onDisconnect.addListener(onDisconnected); 
    updateUiState(); 
} 
document.addEventListener('DOMContentLoaded', function() { 
    document.getElementById('connect-button').addEventListener(
     'click', connect); 
    document.getElementById('send-message-button').addEventListener(
     'click', sendNativeMessage); 
    updateUiState(); 
}); 

Il manifest.json:

{ 
    // Extension ID: knldjmfmopnpolahpmmgbagdohdnhkik 
    "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcBHwzDvyBQ6bDppkIs9MP4ksKqCMyXQ/A52JivHZKh4YO/9vJsT3oaYhSpDCE9RPocOEQvwsHsFReW2nUEc6OLLyoCFFxIb7KkLGsmfakkut/fFdNJYh0xOTbSN8YvLWcqph09XAY2Y/f0AL7vfO1cuCqtkMt8hFrBGWxDdf9CQIDAQAB", 
    "name": "Native Messaging Example", 
    "version": "1.0", 
    "manifest_version": 2, 
    "description": "Send a message to a native application.", 
    "app": { 
    "launch": { 
     "local_path": "main.html" 
    } 
    }, 
    "icons": { 
    "128": "icon-128.png" 
    }, 
    "permissions": [ 
    "nativeMessaging" 
    ] 
} 

Il Registro:

01.235.164,106174 millions
REG ADD "HKCU\Software\Google\Chrome\NativeMessagingHosts\com.google.chrome.example.echo" /ve /t REG_SZ /d "%~dp0com.google.chrome.example.echo-win.json" /f 

codice C#:

using Newtonsoft.Json; 
using Newtonsoft.Json.Linq; 
using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Text; 

namespace talkWithChromeCSharp 
{ 
    class Program 
    { 
     public static void Main(string[] args) 
     { 
      JObject data; 
      while ((data = Read()) != null) 
      { 
       var processed = ProcessMessage(data); 
       Write(processed); 
       if (processed == "exit") 
       { 
        return; 
       } 
      } 
     } 

     public static string ProcessMessage(JObject data) 
     { 
      var message = data["message"].Value<string>(); 
      switch (message) 
      { 
       case "test": 
        return "testing!"; 
       case "exit": 
        return "exit"; 
       default: 
        return "echo: " + message; 
      } 
     } 

     public static JObject Read() 
     { 
      var stdin = Console.OpenStandardInput(); 
      var length = 0; 

      var lengthBytes = new byte[4]; 
      stdin.Read(lengthBytes, 0, 4); 
      length = BitConverter.ToInt32(lengthBytes, 0); 

      var buffer = new char[length]; 
      using (var reader = new StreamReader(stdin)) 
      { 
       while (reader.Peek() >= 0) 
       { 
        reader.Read(buffer, 0, buffer.Length); 
       } 
      } 

      return (JObject)JsonConvert.DeserializeObject<JObject>(new string(buffer))["data"]; 
     } 

     public static void Write(JToken data) 
     { 
      var json = new JObject(); 
      json["data"] = data; 

      var bytes = System.Text.Encoding.UTF8.GetBytes(json.ToString(Formatting.None)); 

      var stdout = Console.OpenStandardOutput(); 
      stdout.WriteByte((byte)((bytes.Length >> 0) & 0xFF)); 
      stdout.WriteByte((byte)((bytes.Length >> 8) & 0xFF)); 
      stdout.WriteByte((byte)((bytes.Length >> 16) & 0xFF)); 
      stdout.WriteByte((byte)((bytes.Length >> 24) & 0xFF)); 
      stdout.Write(bytes, 0, bytes.Length); 
      stdout.Flush(); 
     } 
    } 
} 

file di com.google.chrome.example.echo-win.json: main.html

{ 
    "name": "com.google.chrome.example.echo", 
    "description": "Chrome Native Messaging API Example Host", 
    "path": "native-messaging-example-host.bat", 
    "type": "stdio", 
    "allowed_origins": [ 
    "chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/" 
    ] 
} 

HTML:

<!DOCTYPE html> 

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <meta charset="utf-8" /> 
    <script src='main.js'></script> 
</head> 
<body> 
    <button id='connect-button'>Connect</button> 
    <input id='input-text' type='text' /> 
    <button id='send-message-button'>Send</button> 
    <div id='response'></div> 
</body> 
</html> 
.210

mia struttura di directory in Visual Studio:

C:\Users\t||||||\Documents\Visual Studio 2012\Projects\talkWithChromeCSharp\talkWithChromeCSharp 
    -APP 
    |-icon-128.png 
    |-main.html 
    |-main.js 
    |-manifest.json 
    -bin 
    |-Debug 
     |-Newtonsoft.Json.dll 
     |-talkWithChromeCSharp.exe 
     |-etc etc... 
    |-Release 
    -obj 
    -Properties 
    -regs 
    |-com.google.chrome.example.echo-win.json 
    |-install_host.bat 
    |-etc etc... 

Dopo l'avvio di debug CONTRO I installare il plugin e caricare il file main.html sul browser Chrome e fare clic sul pulsante "Connetti". Questo è quando ricevo quell'errore.

Cosa mi manca?

UPDATE

Questo è l'ID corretto per esso. L'ho tenuto in quel modo poiché immagino che "KEY" sia ciò che determina l'ID.

enter image description here enter image description here

+0

" "allowed_origins": [ "cromo-extension: // knldjmfmopnpolahpmmgbagdohdnhkik /" ] "-> che è una copia incolla dalla pagina di esempio .. wha t è il tuo ID di estensione? prova a utilizzare quello giusto – DannyZB

+0

@DanielBatkilin che non è corretto. È l'ID corretto per quella chiave. – StealthRT

+0

@Teepeemm Ho cambiato il tag. Grazie per la segnalazione. – StealthRT

risposta

2

non si dovrebbe aprire main.html direttamente, ma piuttosto dal di Avvio applicazioni di Chrome a chrome: // apps/

+1

SÌ - lanciando da 'chrome: // apps /' ha funzionato. Ma come posso lanciarlo come 'http: // localhost' o' https: // myserver.com/sameapp' e connetterti allo stesso modo? – YumYumYum

+1

Non ne sono completamente sicuro, ma penso che tu aggiunga l'app al Chrome Web Store e le persone lo installino localmente. – Chet

+0

Vedere questo è il problema, non è mai stato ben documentato come usarlo da http: // o https: //. ho bisogno di usarlo non usando chrome: // concetto di app. – YumYumYum

1

Attenzione copia-incolla!

https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/nativeMessaging/app/manifest.json

Parto dal presupposto che è dove avete ottenuto il vostro manifesto. Sostituire la "chiave" con quella corretta

e in "allowed_origins" utilizzare l'ID estensione reale al posto di quello dell'esempio

https://developer.chrome.com/apps/manifest/key

Ci possono essere più errori là, ma questi sono solo quelli che catturo in un primo sguardo.

1

Dal momento che si sta utilizzando progetto C# che generano un file exe come output, il file di native-messaging-example-host.bat non deve essere come esempio originale che era sth così:

python "%~dp0/native-messaging-example-host" %* 

Invece, il file batch dovrebbe cambiare come segue:

@echo off 
Pushd C:\Users\h.aghajani\Desktop\host /*Path directory of your exe*/ 
start native-messaging-example-host.exe /*Name of the execution file*/ 
6

Troppe confusioni e non ben spiegato che ha funzionato davvero per me. Quindi, sto cercando di creare un documento `` idiot proof`. (Si prega di migliorare questa versione)

Obiettivo: sistema operativo Windows, Google Chrome fino alla versione 50 testate, comunichino alla applicazione nativa


Fase 1:


download: https://developer.chrome.com/extensions/examples/api/nativeMessaging/app.zip

Fase 2:


carico l'applicazione scaricata da Google Chrome

enter image description here

Fase 3:


a) aggiungere la chiave del Registro

REG ADD "HKLM\Software\Google\Chrome\NativeMessagingHosts\com.google.chrome.example.echo" /ve /t REG_SZ /d "C:\\run-my-exe\\manifest.json" /f

enter image description here

b) Per effettuare una cromato esecutore personalizzato, copiare il seguente in C: \ Run-my-exe \ run-cromo.bat:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --enable--native-messaging --native-messaging-hosts="com.google.chrome.example.echo=C:\\run-my-exe\\manifest.json"

Fase 4: Host


a) put seguente in C: \ Run-my-exe \ manifest.json

{ 
    "name": "com.google.chrome.example.echo", 
    "description": "Chrome Native Messaging API Example Host", 
    "path": "native-messaging-example-host.bat", 
    "type": "stdio", 
    "allowed_origins": [ 
    "chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/" 
    ] 
} 

b) metti seguente in C: \ run-my-exe \ nativo-messaging-examp le-host.bat

@echo off 
cd %windir%\system32 
start calc.exe 

Fase 5: Come faccio ora eseguo?


a) cromato aperto con questo script: C:\\run-my-exe\\run-chrome.bat

b) nel Chrome andare a chrome://apps

c) lancio

tramite l'icona

enter image description here

non

come di seguito:

enter image description here

Risultato finale:

enter image description here

+0

Grazie per queste istruzioni. All'inizio non funzionava per me, ma è ora. Avevo già provato l'app e avevo la stessa chiave di registro sia per l'utente corrente che per la macchina locale. La chiave utente corrente non era valida. Dopo aver cancellato e rieseguito, ho il calcolo. Una domanda, c'è un modo per chiamare l'exe con un parametro? – JustAspMe

+2

@YumYumYum, ** Ma aspetta **, Google non rimuoverà le app di Chrome da Chrome entro il 2018? Vedi https://blog.chromium.org/2016/08/from-chrome-apps-to-web.html quindi, in altre parole, non funzionerà più in futuro? Ho inviato una richiesta all'indirizzo https://docs.google.com/forms/d/e/1FAIpQLSenHdpA8_eqKiVOrWDjWe_KTfJmoSBEqFIh6SMwQ-NRDJnx1Q/viewform per richiederlo per l'inclusione in futuro, ma abbiamo bisogno di più persone che dicano al team di Chrome che la messaggistica nativa è Importante. – Pacerier

+0

NO: consente di chiudere le app di Chrome da Google Chrome, stanno spaventando il pianeta, poiché la community dovrebbe essere Google Chrome e Google Chrome non dovrebbe governarci. – YumYumYum