| 分享时间 | 2024-11-17 19:41 |
| 最后更新 | 2024-11-20 02:07 |
| 修订版本 | 4 |
| 用户许可 | -未设置- |
| Quicker版本 | 1.43.43 |
| 动作大小 | 11.1 KB |
原理:思源实现的是基于websocket的消息广播系统,因此多个客户端之间可以通过服务器中转实现互发消息。
需要再在思源笔记中添加以下js代码片段
(() => {
// 默认渠道名,可以根据需要修改
const channel = 'siyuan-runjs';
// 创建socket客户端
createSocketClient(channel);
// 当收到消息时被调用
function onReceivedMessage(event) {
let request = parseJson(event.data);
let result = '';
try {
result = (new Function(request.code))();
} catch (e) {
result = e.message || '';
console.error(e);
}
if(request.fromChannel) {
postMessage(request.fromChannel, result);
}
}
// 创建socket客户端
function createSocketClient(channel) {
// 连接 WebSocket 服务器
const socket = new WebSocket('ws://'+location.host+'/ws/broadcast?channel='+channel);
socket.onopen = function(e) {
console.log('Channel '+channel+' connectioned!');
};
socket.onmessage = onReceivedMessage;
socket.onclose = function(event) {
console.log('Channel '+channel+' closed!');
};
socket.onerror = function(error) {
console.error('WebSocket Error:', error);
};
return socket;
}
// 客户端向服务器发送消息
function sendMessage(socket, message) {
if (socket.readyState === WebSocket.OPEN) {
socket.send(message);
} else {
console.error('WebSocket connection is not open');
}
}
// 服务器向客户端发消息
async function postMessage(channel, message) {
const result = await fetchSyncPost('/api/broadcast/postMessage', {
channel: channel,
message: message
});
if(result.code !== 0 || !result.data) {
console.error('postMessage error', result);
}
}
// 解析json
function parseJson(jsonString) {
let json = {};
try {
json = JSON.parse(jsonString || '{}');
} catch(e) {
json = {};
console.error('parseJson error', e);
}
return json;
}
// 发送api请求
async function fetchSyncPost(url, data, returnType = 'json') {
const init = {
method: "POST",
};
if (data) {
if (data instanceof FormData) {
init.body = data;
} else {
init.body = JSON.stringify(data);
}
}
try {
const res = await fetch(url, init);
const res2 = returnType === 'json' ? await res.json() : await res.text();
return res2;
} catch(e) {
console.log(e);
return returnType === 'json' ? {code:e.code||1, msg: e.message||"", data: null} : "";
}
}
})()quicker里如果想实现给思源发消息或执行js,推荐子程序 https://getquicker.net/SubProgram?id=cb322876-e4a3-462a-e322-08dd0733f195 使用可参考它的演示动作 https://getquicker.net/Sharedaction?code=0557062c-aecb-4942-e321-08dd0733f195
| 修订版本 | 更新时间 | 更新说明 |
|---|---|---|
| 4 | 2024-11-20 02:07 | 兼容思源段http模式请求的代码 |
| 3 | 2024-11-18 15:14 | 把关闭连接放到最后,防止影响性能 |
| 2 | 2024-11-18 10:54 | 发现quicker关闭websocket连接竟然划分5秒多,先把这个放到后面。 |