我正在嘗試將當前活動選項卡的 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" %*
清單APP.json:
{
"name": "com.ytdlp.batdlvideo",
"description": "Youtube-dlp",
"path": "C:\\Users\\.....\\native-apps\\dlvideo\\yt_dlp.bat",
"type": "stdio",
"allowed_origins": [
"chrome-extension://-extensionid-/"
]
}
有人可以幫忙嗎?
uj5u.com熱心網友回復:
好的,我認為在我的情況下,問題是只有一條訊息發送到主機,而主機在發送時還沒有準備好?
好吧,這至少是對我有用的代碼:
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 %*
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/382327.html
標籤:javascript Python 批处理文件 谷歌浏览器扩展 chrome-native-消息传递
下一篇:拋出例外:System.Drawing.Common.dll中的“System.IO.FileNotFoundException”
