chatgpt越来越火了,我也来蹭一波热度 思路是这样的:开发一个chrome插件,在网页中选中文字,右键选中chatgpt菜单,将选中文字提交到 chatgpt,然后返回搜索结果。 当然开始之前,你需要注册chatgpt,获取到相关使用密钥 一。先在chrome插件里注册配置调用的密钥页面
{
"name": "chatGpt插件",
"description": "chatGpt插件",
"version": "1.0",
"manifest_version": 2,
"options_page": "options.html",
"permissions": ["contextMenus","activeTab","storage","notifications"],
"icons": {
"16": "icon-bitty.png",
"48": "icon-small.ico",
"128": "icon-large.ico"
},
"csp":"script-src 'self' 'unsafe-inline'; object-src 'self'",
"content_security_policy":"script-src 'self' 'unsafe-eval'; object-src 'self'",
"background": {
"scripts": ["jquery.js","background.js"]
}
}
配置页面为options.html,示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="options.js"></script>
<title>options</title>
</head>
<body>
<h1>chatGpth密钥</h1>
<textarea id="secretKey" cols="100"></textarea>
<button id="saveButton" > 保存</button>
</body>
</html>
配置页面为options.js,示例代码如下:
window.onload=function (){
//默认选择
chrome.storage.local.get('secretKey', function(valueArray) {
console.log(valueArray);
document.getElementById('secretKey').value=valueArray;
});
chrome.storage.sync.get({
secretKey: '',
}, function(items) {
document.getElementById('secretKey').value = items.secretKey;
});
document.getElementById ("saveButton"). onclick= function (e) {
chrome.storage.sync.set({
secretKey: document.getElementById('secretKey').value
}, function() {
});
}
}
将配置的密钥存在chrome.storage,效果如下:
image.png
二。配置background.js,实现选中文字调用chatgpt接口
chrome.storage.sync.get({
secretKey: '',
}, function(items) {
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer '+items.secretKey);
}
});
});
function selectionOnClick(info, tab) {
$.ajax({
type: "POST",
url: "https://api.openai.com/v1/completions",
contentType : "application/json",
dataType : "json",
data: JSON.stringify({
"model": "text-davinci-003",
"prompt": info.selectionText,
"max_tokens": 250,
"temperature": 0
}),
complete: function(result) {
var response = JSON.parse(result.responseText);
alert(response['choices'][0]['text'] )
show('chatgpt',response['choices'][0]['text'])
}
});
}
chrome.contextMenus.create({"title": "chatgpt","contexts":["selection"],"onclick":selectionOnClick});
//通知相关
function show(title,content) {
new Notification(title, {
icon: 'icon-large.ico',
body: content
});
}
效果如下:
image.png
image.png
因为接口是在外国,有点慢,要5-6秒才能出现结果,如果有代理,估计会更快一些。