【问题标题】:How to send/receive text message via nativeMessaging in Chrome?如何在 Chrome 中通过 nativeMessaging 发送/接收短信?
【发布时间】:2022-01-09 16:23:34
【问题描述】:

我正在尝试将当前活动选项卡的 url 发送到 python 脚本。我的扩展程序已经开始运行脚本并尝试发送 url。但是,到目前为止,我还没有成功接收到带有运行脚本的 url。

popup.js:

dlvideo.addEventListener("click", async () => {
    chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
        // Get current url
        url = tabs[0].url;
        
        // Connect to python script
        port = chrome.runtime.connectNative('com.ytdlp.batdlvideo');
        port.onDisconnect.addListener(function() {
            console.log("Disconnected");
        });
        port.onMessage.addListener(function(msg) {
            console.log("Received" + msg);
        });

        // Send url to script
        port.postMessage({ text: url });
    });
});

dlvideo.py(代码似乎在 while 循环开始时卡在此处):

import sys

if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

url = None
while True:
    # The loop seems to get stuck here:
    text_length_bytes = sys.stdin.read(4)

    if len(text_length_bytes) == 0:
        print("test.py: sys.exit0")
        sys.exit(0)
        
    text_length = struct.unpack('i', text_length_bytes)[0]
    text = sys.stdin.read(text_length).decode('utf-8')
    if text.startswith('http'):
        url = text
        print(str(url))
        break
    else:
        print(text)

其他文件可能不相关,但我将它们放在这里以防万一: yt_dlp.bat:

@echo off
start cmd /k python "%~dp0/dlvideo.py" %*

manifestAPP.json:

{
    "name": "com.ytdlp.batdlvideo",
    "description": "Youtube-dlp",
    "path": "C:\\Users\\.....\\native-apps\\dlvideo\\yt_dlp.bat",
    "type": "stdio",
    "allowed_origins": [
        "chrome-extension://-extensionid-/"
    ]
}

有人可以帮忙吗?

【问题讨论】:

    标签: javascript python batch-file google-chrome-extension chrome-native-messaging


    【解决方案1】:

    好的,我认为问题在于只向主机发送了一条消息,而主机在发送时还没有准备好?

    嗯,这至少是对我有用的代码:

    popup.js 和 manifestAPP.json 可以保持不变。

    dlvideo.py:

    import struct
    import json
    import sys
    import os
    
    # Changes the stdio-mode
    if sys.platform == "win32":
        import os, msvcrt
        msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    
    # Read native message from chrome window
    text_message_length = sys.stdin.buffer.read(4)
    text_length = struct.unpack("i", text_message_length)[0]
    text_decoded = sys.stdin.buffer.read(text_length).decode("utf-8")
    text_asstr = json.loads(text_decoded)
    
    # Get URL
    url = text_asstr['text']
    

    yt_dlp.bat:

    @echo off
    python dlvideo.py %*
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 2020-04-01
      • 2012-07-06
      相关资源
      最近更新 更多