You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过浏览器控制台模拟回车键发送Slack消息?

解决Slack控制台自动发送消息的问题

你之前碰到的卡点,核心是Slack的前端不是传统的表单提交模式,而且直接修改DOM内容不会触发它内部框架的状态更新,旧的按键模拟方式也不兼容现代浏览器。下面给你一套可行的解决方案:

步骤1:让Slack识别到输入内容

直接修改ql-editor里的<p>标签内容后,必须触发input事件,才能让Slack的前端框架感知到输入框内容变化:

const inputParagraph = document.getElementById("msg_input").querySelector(".ql-editor p");
inputParagraph.innerHTML = "Hi";
// 触发input事件更新框架状态
inputParagraph.dispatchEvent(new Event('input', { bubbles: true }));

步骤2:模拟发送消息的正确方式

方法一:直接触发发送按钮的点击事件

Slack的发送按钮有固定的类名标识,你可以直接找到它并触发点击:

const sendButton = document.querySelector(".p-message_input_send_button");
if (sendButton) {
  sendButton.click();
}

方法二:兼容现代浏览器的回车事件模拟

如果想用回车触发发送,要使用标准的KeyboardEvent构造函数,指定keycode属性(旧的keyCode已经被现代浏览器废弃):

const inputBox = document.getElementById("msg_input").querySelector(".ql-editor");
// 模拟keydown事件
const keydownEvent = new KeyboardEvent('keydown', {
  key: 'Enter',
  code: 'Enter',
  bubbles: true,
  cancelable: true
});
inputBox.dispatchEvent(keydownEvent);

// 模拟keyup事件
const keyupEvent = new KeyboardEvent('keyup', {
  key: 'Enter',
  code: 'Enter',
  bubbles: true,
  cancelable: true
});
inputBox.dispatchEvent(keyupEvent);

完整循环发送示例

把上面的逻辑整合到循环里,记得加一点延迟,避免Slack的频率限制或者前端处理不过来:

async function sendHiMultipleTimes(times) {
  const inputParagraph = document.getElementById("msg_input").querySelector(".ql-editor p");
  const sendButton = document.querySelector(".p-message_input_send_button");
  
  for (let i = 0; i < times; i++) {
    // 设置输入内容并触发框架更新
    inputParagraph.innerHTML = "Hi";
    inputParagraph.dispatchEvent(new Event('input', { bubbles: true }));
    
    // 点击发送按钮
    sendButton.click();
    
    // 等待1秒再发下一条,防止被Slack限制
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
}

// 调用函数发送10次Hi
sendHiMultipleTimes(10);

为什么之前的方法无效?

  • 表单submit():Slack的消息发送是通过内部API请求完成的,根本不是传统表单提交,调用submit()只会导致页面错误重载。
  • 旧keycode模拟:现代浏览器已经逐步废弃keyCode属性,改用keycode来标识按键,所以你之前的模拟事件不会被Slack的前端识别。

内容的提问来源于stack exchange,提问作者paradocslover

火山引擎 最新活动