效果如下:
9629a0e44b9291dcd04427cb85afaa7.png (24.69 KB, 下载次数: 0)
下载附件
2024-8-5 10:19 上传
3901419f4544bcb28c3a31cacf59f39.png (29.77 KB, 下载次数: 0)
下载附件
2024-8-5 10:19 上传
bbd26d43ec5d17df04aab8c5a22b9bc.png (24.23 KB, 下载次数: 0)
下载附件
2024-8-5 10:19 上传
python代码如下:
[Python] 纯文本查看 复制代码from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from pydantic import BaseModel
from typing import Dict, List
app: FastAPI = FastAPI()
class WebSocketClient:
websocket: WebSocket
def __init__(self, websocket: WebSocket):
self.websocket = websocket
class BroadcastMessage(BaseModel):
"""
客户端传过来的消息
"""
type: str # 消息类型,对应前端的console对象
content: str # 消息内容
css: str = None # css样式,可以自定义颜色显示
# 全局字典,键名为客户端id,值为 WebSocketClient 对象列表
clients: Dict[str, List[WebSocketClient]] = {}
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: str = ''):
await websocket.accept()
if client_id not in clients:
clients[client_id] = []
clients[client_id].append(WebSocketClient(websocket=websocket))
try:
while True:
data = await websocket.receive()
if data.get('type') == 'websocket.disconnect':
print('断开连接')
# 客户端发送了断开连接消息,删除该客户端
clients[client_id] = [client for client in clients[client_id] if client.websocket != websocket]
if not clients[client_id]:
del clients[client_id]
return
except WebSocketDisconnect:
# 移除断开连接的 websocket 对象
clients[client_id] = [client for client in clients[client_id] if client.websocket != websocket]
if not clients[client_id]:
del clients[client_id]
@app.post("/broadcast/{client_id}")
async def broadcast_message(message: BroadcastMessage, client_id: str = ''):
if client_id in clients:
for client in clients[client_id]:
try:
await client.websocket.send_json(message.model_dump_json())
except WebSocketDisconnect:
# 如果发送失败,移除断开连接的 websocket 对象
clients[client_id] = [c for c in clients[client_id] if c.websocket != client.websocket]
if not clients[client_id]:
del clients[client_id]
return {"status": "message sent"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
第一次写chrome扩展,感觉跟开发小程序差不多,只要会js,参考官方文档就可以了,就是manifest_version的版本区别有点大,目前代码有的是3版本,2的版本要废弃了。如果是自己使用的话,那么可以在浏览器把源码包导入进去,要分享给别人使用需要上架到应用市场。
chrome源码里有一个log.js,有兴趣大家可以扩展一下,可以把日志存储到缓存里,再写一个页面读取出来方便搜索。
[JavaScript] 纯文本查看 复制代码
chrome.runtime.onMessage.addListener(
function(logs) {
logs = typeof logs === 'string' ? JSON.parse(logs) : logs;
// console.debug(logs);
if ("object" != typeof logs) {
return;
}
// 目前服务器只返回一个对象类型
const log = logs;
if (console[log.type]) {
if (log.css) {
console[log.type]("%c" + log.content, log.css);
} else {
console[log.type](log.content);
}
if ("alert" === log.type) {
alert(log.content);
}
return;
}
console.error("SocketLog type error, ", logs);
// alert("SocketLog type error, ");
}
);