4

네이티브 메시징을 통해 Chrome 확장 프로그램과 통신 할 수있는 PHP 클래스를 작성하려고합니다.PHP와의 크롬 네이티브 메시징

나는 내 코드에 연결할 수 있지만, 시작에서 크롬 내 PHP 콘솔 응용 프로그램으로

chrome-extension://lkjcciocnocjjgpacggbaikjehbfedbl/ --parent-window=1837060 

(호스트)를 보냅니다. 연결을 작동 시키려면 무엇을 대답해야합니까? 아래 코드는 PHP 코드입니다. 그렇습니다. POC 프로젝트이므로 더러워요. 특히 현재 업데이트 된 Chrome 확장 프로그램을 처음 접해 보았습니다.

function out($data = ""){ 
    $fp = fopen("php://stdout", "w"); 
    if($fp){ 
     $response = array("text" => "Ok"); 
     $message = json_encode($response); 
     fwrite($fp, $message); 
     fflush($fp); 
     slog("[OUTPUT] " . json_encode($response)); 
     fclose($fp); 
     exit(0); 
    }else{ 
     slog("Can't open output stream."); 
     exit(1); 
    } 
} 

function err($data){ 
    $fp = fopen("php://stderr", "w"); 
    if($fp){ 
     fwrite($fp, $data); 
     fflush($fp); 
     fclose($fp); 
    } 
    return; 
} 

function in(){ 
    $data = ""; 
    $fp = fopen("php://stdin", "r"); 
    if($fp){ 
     $data = fgets($fp); 
     fclose($fp);  
    }else{ 
     slog("Can't open input stream."); 
     exit(1); 
    } 
    slog("[INPUT]" . $data); 
    return $data; 
} 

function slog($data){ 
    if($data != ""){ 
     file_put_contents("./log.txt", date("r").": {$data}\r\n", FILE_APPEND); 
    } 
} 

slog("Entering"); 
while(true){ 
    if(($l = in()) !== ""){ 
     out($l); 
    }else{ 
     exit(0); 
    } 
} 
exit(0); 

내 background.js 코드. (확장 기능)

var port = null; 
var hostName = "com.google.chrome.poc-extension"; 

function appendMessage(text) { 
    document.getElementById('response').innerHTML += "<p>" + text + "</p>"; 
} 

function updateUiState() { 
    if (port) { 
     document.getElementById('connect-button').style.display = 'none'; 
    }else{ 
     document.getElementById('connect-button').style.display = 'block'; 
    } 
} 

function sendNativeMessage() { 
    port = chrome.runtime.connectNative(hostName); 
    port.onMessage.addListener(onNativeMessage); 

    message = {"text": document.getElementById('input-text').value}; 
    port.postMessage(message); 
    appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>"); 
} 
function onNativeMessage(message) { 
    alert(message); 
    appendMessage("Received message: <b>" + JSON.stringify(message) + "</b>"); 
} 
function onDisconnected() { 
    appendMessage("Failed to connect: " + chrome.runtime.lastError.message); 
    console.log(chrome.runtime.lastError); 
    port = null; 
    updateUiState(); 
} 
function connect() { 
    appendMessage("Connecting to native messaging host <b>" + hostName + "</b>") 
    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(); 
}); 

예제 응용 프로그램이 있지만 정확히 무엇을 얻지 못합니다. 게다가 그것은 내가 원하지 않는 Tkinter 플러그인을 사용합니다. 깨끗하고 평이하며 심플한 확장 기능을 원합니다.

+0

제 인용구는 표준 입력으로 전송되지 않고, 그 커맨드 라인 파라미터이다. 귀하의 PHP 코드에서 그것을 보면 뭔가 잘못되었습니다. 파이썬 예제에서 의미있는 부분은 send_message와 read_thread_func입니다. [프로토콜] (https://developer.chrome.com/extensions/nativeMessaging#native-messaging-host-protocol)은 간단하며 ** 4 바이트 길이 **, JSON-ified 메시지에 설명되어 있습니다. – wOxxOm

+0

실제로 그럴듯한 소리. 곧 확인하고 회신하겠습니다. –

+0

@wOxxOm 크롬이 stdin을 올바르게 파이프하지 않는 것 같습니다. 예를 들어 파이썬 응용 프로그램과 같은 windows .bat 파일을 사용합니다. '''echo % * | php -f "% ~ dp0/native_host.php"''' –

답변

7

네이티브 메시징은 읽기 및 쓰기를 위해 구조화 된 데이터 (길이 형식)를 사용합니다. 브라우저 (자바 스크립트)에서 구조가 브라우저에 의해 처리되었습니다. 네이티브 메시징과 통신하려면 해당 구조를 따라야합니다. Read refference here

각 메시지 JSON을 사용하여 직렬화하고, UTF-8 인코딩되고 네이티브 바이트 순서로 32 비트의 메시지 길이 선행된다. len(message) + [your message]

렌 (메시지) 프로토콜 다음과 같은 포장해야합니다

그래서 당신은 당신의 메시지를 보내야합니다.

예 함수의 출력을 보내도록 :

function out($data = ""){ 
    $fp = fopen("php://stdout", "w"); 
    if($fp){ 
     $response = array("text" => "Ok"); 
     $message = json_encode($response); 
     //Send the length of data 
     fwrite($fp, pack('L', strlen($message))); 
     fwrite($fp, $message); 
     fflush($fp); 
     slog("[OUTPUT] " . json_encode($response)); 
     fclose($fp); 
     exit(0); 
    }else{ 
     slog("Can't open output stream."); 
     exit(1); 
    } 
} 

는 입력을 읽는다

function in(){ 
    $data = ""; 
    $fp = fopen("php://stdin", "r"); 
    if($fp){ 
     //Read first 4 bytes as unsigned integer 
     $len = current(unpack('L', fread($fp, 4))); 
     $data = fread($fp, $len); 
     fclose($fp); 
    }else{ 
     slog("Can't open input stream."); 
     exit(1); 
    } 
    slog("[INPUT]" . $data); 
    return $data; 
}