javascript - 使用 PHP 的 Chrome native 消息传递

标签 javascript php google-chrome-extension chrome-native-messaging

我正在尝试构建一个可以通过 native 消息传递与 Chrome 扩展进行通信的 PHP 类。

我可以连接到我的代码,但在启动时 Chrome 会发送

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

到我的 PHP 控制台应用程序(The Host)。我要回复什么才能使连接正常工作? 在我的 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();
});

this Python示例应用程序,但我真的不明白它到底做了什么。除此之外,它还使用了我不想要的 Tkinter 插件。我想要一个干净、简单和简单的扩展。

最佳答案

Native Messaging 使用结构化数据(长度格式)进行读写。在浏览器(JavaScript)中,该结构已由浏览器处理。如果你想与 Native Messaging 进行通信,那么你需要遵循该结构。 Read refference here

Each message is serialized using JSON, UTF-8 encoded and is preceded with 32-bit message length in native byte order.

因此您需要将消息发送为:len(message) + [your message]

len(message) 必须按照协议(protocol)打包。

发送输出的示例函数:

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;
}

关于javascript - 使用 PHP 的 Chrome native 消息传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47269500/

相关文章:

javascript - 如何使用 react redux 配置 mapDispatchToProps?

php - 如何避免对mysql查询进行子查询

javascript - React DatePicker 加载默认值,但当状态改变时不会改变

javascript - 如何同时托管 socket.io 服务器和 http 服务器?

javascript - Express 将外部 Json 渲染为 jade

php - 在选择框中显示数据库的列

php - PHPMyadmin 中的数据库客户端版本

javascript - 内容脚本中的动态脚本加载

google-chrome - Google Chrome 扩展程序可以像主题一样更改浏览器的外观吗?

python - 使用 Python 通过 Selenium WebDriver 打开 chrome 扩展