zhengbangbo/chat-gpt-userscript

[Bug Report]多次点击Deepl 翻译按钮频繁闪烁不同文本流

duck123ducker opened this issue · 3 comments

Describe the bug
在deepl翻译页面中,当一个文本流没输出完全时,多次点击翻译按钮,会触发多个翻译进程并频繁闪烁不同进程的文本流。

To Reproduce
Steps to reproduce the behavior:

  1. 打开deepl页面
  2. 输入框随便输入
  3. 多次点击翻译按钮
  4. See error

Expected behavior
新的翻译文本流完全覆盖旧的文本流。

Desktop or Mobile (please complete the following information):

  • OS: Windows10
  • Browser: Chrome
  • Userscript Manager: Tampermonkey
  • Userscript Version: v0.6.1

Additional context
可以每点击一次按钮就添加一个新的容器或者终止旧的接收文本流函数,脚本中的container相关函数深度定制化,看起来设定一个全局flag变量用来在getanswer过程中通过判断按钮是否被重新点击来决定是否终止此次接收文本流比重新创建容器要简单一些。

大概这样就临时解决了,就添加几行flag相关的内容。

var flag=0;//定义flag
button.addEventListener("click", function() {
  flag++;//点击增加
}
async function getAnswer(question) {
  let oldFlag=flag;//定义开始获取信息流时的flag
  function onloadend() {
    if (event.response) {
      const answer = JSON.parse(event.response.split("\n\n").slice(-3, -2)[0].slice(6)).message.content.parts[0];
      if(oldFlag !== flag) return;//如果变化则不输出
      containerShow(answer);
    }
  };
  function onloadstart() {
    if (responseItem.startsWith("data: {")) {
      console.log("responseItem.slice(6): ", responseItem.slice(6));
      const answer = JSON.parse(responseItem.slice(6)).message.content.parts[0];
      if(oldFlag !== flag) return;//如果变化则停止输出
      containerShow(answer);
     }
  }
}

谢谢你的提供的方案,我找到一个可能更好的方案:

给 getAnswer 加一个回调,当请求完成之后解除按钮 disabled 属性。