New script baidu.com

2023/12/31 13:10:52

Fra og med 01.01.2024. Se den nyeste version.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name        New script baidu.com
// @namespace   Violentmonkey Scripts
// @match      *://www.baidu.com/s*
// @match      https://www.baidu.com/*
// @grant      GM_setClipboard
// @grant      GM_addStyle
// @grant      GM_getResourceText
// @require    https://cdn.bootcdn.net/ajax/libs/showdown/2.1.0/showdown.min.js
// @require    https://cdn.bootcdn.net/ajax/libs/highlight.js/11.7.0/highlight.min.js
// @require    https://cdn.bootcdn.net/ajax/libs/toastr.js/2.1.4/toastr.min.js
// @resource toastCss  https://cdn.bootcdn.net/ajax/libs/toastr.js/2.1.4/toastr.min.css
// @grant       none
// @version     1.0
// @author      yang
// @description 2023/12/31 13:10:52
// @license    MIT
// ==/UserScript==
console.log("加载脚本:" + new Date());


window.onload=function(e){
  creatBox();
}

//全局变量 存储搜索关键字
var keyWord="";


// if (window.location.href.indexOf("baidu.com\/s") > -1) {
//   var query = document.getElementById("kw").value;
//   console.log("用户输入的搜索词:" + query);
//   PostData(query);
// }

//绘画输出框
function creatBox() {
  GM_addStyle(GM_getResourceText("toastCss"))

  let divE = document.createElement('div');
  //divE.classList.add("markdown-body");
  divE.innerHTML = `
                <div>
                <textarea id="story" name="story" rows="1" cols="33">It was a dark and stormy night...</textarea>
                <button id='CusomBtn' onclick="">查询</button>
                </div>
                <div class="card">
                  <article id="gptAnswer" class="markdown-body">请稍等一会...</article>
                </div>

                <style>
                pre .btn-pre-copy{
                        text-align: right;
                        display: block;
                    }

                    pre .btn-pre-copy:hover{
                        cursor: pointer;
                    }
                .card {
                   border: 0.5px solid #ccc; /* 设置边框 */
                   background-color: #fff; /* 设置背景颜色 */
                   padding: 5px; /* 设置内部间距 */
                   /*margin: 10px; /* 设置外部间距 */
                   border-radius: 5px; /* 添加圆角效果 */
                   max-height:600px;
                  overflow: hidden;
                  overflow-y: scroll;
                }
                </style>
              `;
  let NewDom = document.getElementById("gptAnswer");
  let content_right = document.getElementById('content_right');
  if (NewDom === null && content_right !== null) {
    content_right.prepend(divE);
    //监听自定义搜索事件
  document.getElementById("CusomBtn").addEventListener("click", function(event) {
     var query = document.getElementById("story").value;
      // 执行你的搜索操作或其他逻辑
      console.log("自定义搜索词:" + query);
      creatBox();
      //执行获取
      PostData(query);
  });
  }
}

// //监听回车搜索事件
// document.getElementById("kw").addEventListener("keydown", function(event) {
//   if (event.keyCode === 13) {
//     // 回车键被按下
//     //event.preventDefault(); // 阻止默认的提交行为
//     var query = document.getElementById("kw").value;
//     // 执行你的搜索操作或其他逻辑
//     console.log("用户输入的搜索词:" + query);
//     creatBox();
//     //执行获取
//     PostData(query);
//     //let test = "在JavaScript中,没有`js++`这样的语言。我猜您可能是指JavaScript语言中的递归。递归是一种算法设计技术,其中函数可以调用自身来解决问题。以下是一个使用JavaScript实现递归的示例:\n\n```javascript\nfunction factorial(n) {\n  if (n === 0) {\n    return 1;\n  } else {\n    return n * factorial(n - 1);\n  }\n}\n\nconsole.log(factorial(5)); // 输出 120\n```\n\n在上面的示例中,`factorial`函数使用递归来计算一个数的阶乘。当传入的参数`n`为0时,函数返回1作为基本情况。否则,函数将`n`与`factorial(n - 1)`的结果相乘,从而实现递归调用。这个递归过程一直持续到`n`的值为0,然后逐层返回结果,最终计算出整个阶乘的值。\n\n请注意,递归算法需要小心处理终止条件,以避免无限递归导致堆栈溢出。在实际使用中,还需要考虑性能和效率方面的问题。"
//   }
// });
// //监听回车搜索事件
// document.getElementById("su").addEventListener("click", function(event) {
//    var query = document.getElementById("kw").value;
//     // 执行你的搜索操作或其他逻辑
//     console.log("用户输入的搜索词:" + query);
//     creatBox();
//     //执行获取
//     PostData(query);
// });

setInterval(()=>{
  let key = getUrlParam(window.location.href,'wd');
  if(key!==keyWord){
    keyWord = key;
    creatBox();
    //执行获取
    PostData(keyWord);
  }
});





function CusomBtn(){
  let key = document.getElementById("story").value;
  PostData(key);
}

function getUrlParam(url, param) {
    const reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)");
    const result = url.substring(url.indexOf('?') + 1).match(reg);
    if (result != null) {
        return decodeURIComponent(result[2]);
    }
    return null;
}

function PostData(query) {
  //document.getElementById('gptAnswer').innerHTML = "请稍等一会儿...";
  var obj = {
    "messages": [{
        "role": "system",
        "content": "\nYou are ChatGPT, a large language model trained by OpenAI.\nKnowledge cutoff: 2021-09\nCurrent model: gpt-3.5-turbo\nCurrent time: 2023/12/31 12:13:57\nLatex inline: $x^2$ \nLatex block: $$e=mc^2$$\n\n"
      },
      {
        "role": "user",
        "content": query
      }
    ],
    "stream": false,
    "model": "gpt-3.5-turbo",
    "temperature": 0.5,
    "presence_penalty": 0,
    "frequency_penalty": 0,
    "top_p": 1
  };
  var httpRequest = new XMLHttpRequest();
  var url = "https://api.nextapi.fun/v1/chat/completions";
  httpRequest.open("POST", url, true);
  httpRequest.setRequestHeader("Content-type", "application/json");
  httpRequest.setRequestHeader("Authorization", "Bearer ak-EEKBm0NsKJh8M6wtb2gfpa0Ytrhg4J0ixvBNjIVIg6xAi6TV");
  httpRequest.send(JSON.stringify(obj)); //发送请求 将json写入send中
  httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        //处理响应结果
        var result = httpRequest.responseText;
        console.log(new Date());
        result = JSON.parse(result);
        console.log(result)
        //console.log(result.choices[0].message.content);
        var message = result.choices[0].message.content;

        // var renderedHTML = marked.parse(message);
        // // console.log(renderedHTML);
        // creatBox();
        // var NewDom = document.getElementById("outputStory");
        // NewDom.innerHTML  = renderedHTML;
        creatBox();
        showAnserAndHighlightCodeStr(message);

      } else {
        //处理请求失败
        alert('请求失败');
      }
    }
  };
};

//显示答案并高亮代码函数
function showAnserAndHighlightCodeStr(codeStr) {
  if (!codeStr) return
  rawAns = codeStr; //记录原文
  try {
    document.getElementById('gptAnswer').innerHTML = mdConverter(codeStr)
  } catch (ex) {
    console.error(ex)
  }
  highlightCodeStr() //高亮
  //添加代码复制按钮 start
  let preList = document.querySelectorAll("#gptAnswer pre")
  preList.forEach((pre) => {
    try {
      if (!pre.querySelector(".btn-pre-copy")) {
        //<span class=\"btn-pre-copy\" onclick='preCopy(this)'>复制代码</span>
        let copyBtn = document.createElement("span");
        copyBtn.setAttribute("class", "btn-pre-copy");
        copyBtn.addEventListener("click", (event) => {
          let _this = event.target
          //console.log(_this)
          let pre = _this.parentNode;
          //console.log(pre.innerText)
          _this.innerText = '';
          GM_setClipboard(pre.innerText, "text");
          _this.innerText = '复制成功'

          setTimeout(() => {
            _this.innerText = '复制代码'
          }, 2000)
        })
        copyBtn.innerText = '复制代码'
        pre.insertBefore(copyBtn, pre.firstChild)
      }
    } catch (e) {
      console.log(e)
    }
  })
  //添加代码复制按钮 end
}


//高亮代码函数
function highlightCodeStr() {
  let gptAnswerDiv = document.querySelector("#gptAnswer");
  gptAnswerDiv.querySelectorAll('pre code').forEach((el) => {
    hljs.highlightElement(el);
  });
}

function mdConverter(rawData) {
  let converter = new showdown.Converter();
  converter.setOption('tables',
    true); //启用表格选项。从showdown 1.2.0版开始,表支持已作为可选功能移入核心拓展,showdown.table.min.js扩展已被弃用
  converter.setOption('openLinksInNewWindow', true) //链接在新窗口打开
  converter.setOption('strikethrough', true) //删除线
  converter.setOption('emoji', true) //开启emoji

  /***
   * original: John Gruber 规范中的原始 Markdown 风格
   * vanilla:对决基础风味(v1.3.1 起)
   * github: GitHub 风格的 Markdown,或 GFM
   */
  showdown.setFlavor('github');

  try {
    return converter.makeHtml(rawData);
  } catch (ex) {
    console.error(ex)
  }
  return rawData;

}