search
HomeTechnology peripheralsAIImplementation of word-marking translation browser script based on ChatGPT API

Preface

Recently there is a browser script based on ChatGPT API on GitHub, openai-translator. In a short period of time, the star has reached 12k. In addition to supporting translation, it also supports polishing and summarizing functions. In addition to In addition to the browser plug-in, tauri is also used to package a desktop client. Putting aside tauri and using the rust part, the browser part is relatively simple to implement. Today we will implement it manually.

Interface provided by openAI

For example, we can copy the following code and initiate a request in the browser console to complete the translation

//示例
const OPENAI_API_KEY = "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";

const prompt = `Translate this into Chinese:
hello world`;
const res = await fetch("https://api.openai.com/v1/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: "text-davinci-003",
prompt,
max_tokens: 1000,
temperature: 0,
}),
});
const response = await res.json();

const result = response.choices[0].text;

OPONAI_API_KEY in the above code needs to be replaced with yours my own.

Realize word translation

Word translation is a common web page function. When the user selects a word or a text, a small window will automatically pop up to display the translation of the word or text.

  1. First, add an empty DIV element and a button that triggers translation in the HTML page
let keyword;
const translation = document.createElement("div"); 
translation.id ="translation"; 
const icon = document.createElement("img"); 
icon.style.width ="30px";
icon.style.height = "30px";
icon.src ="http://example.com/icon.png";
translation.appendChild(icon)
  1. Add a mouse-up event listener to the page , when the user selects a piece of text, set the search keywords.
document.addEventListener("mouseup", (event) => {
const selection = window.getSelection().toString().trim();
if (selection) {
keyword=selection;
}
});
  1. Mouse click to execute translation logic. You can use AJAX requests to get the translation results from the background and display them in a DIV element.
function translate(){
if(keyword){
// 执行翻译逻辑
}
}
icon.addEventListener("mouseover", translate);
  1. Add styles to the DIV element in the CSS style sheet so that it floats and displays on the page.
#translation {
position: fixed;
top: 10px;
right: 10px;
max-width: 300px;
padding: 5px;
background-color: #f7f7f7;
border: 1px solid #ccc;
box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
z-index: 9999;
}

The above steps can realize the basic function of word translation. Let’s take a look at the effect.

基于 ChatGPT API 的划词翻译浏览器脚本实现

react antd implementation

The above code only implements the simplest version, and the style is also It is not beautiful enough, so we can use webpack react antd to implement a modern plug-in. Here I use a previously created template tampermonkey-starter.

Use antd's Popover component to display and use react to reconstruct the js code, we can achieve the following effects.

基于 ChatGPT API 的划词翻译浏览器脚本实现

Word translation

Click the translation button, and the translation result will be displayed through the interface request below. However, the translation results will not be displayed until the api is fully returned, which will be slower. Can we use Stream? Does the OpenAI interface support stream rendering? In this way, the results will pop up word by word.

import { createParser } from "eventsource-parser";

const translate = async (text: string) => {
const resp = await fetch("https://api.openai.com/v1/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
authorization:
`Bearer ${OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: "text-davinci-003",
prompt: `Translate this into Chinese:
${text}`,
max_tokens: 1000,
temperature: 0,
frequency_penalty: 0,
stream: true,
}),
});
if (resp.status !== 200) {
const res = await resp.json();
setLoading(false);
console.error(res);
return;
}
const parser = createParser((event) => {
if (event.type === "event") {
const data = event.data;
if (data === "[DONE]") {
setLoading(false);
}
try {
let json = JSON.parse(event.data);
setResult((prev) => {
return prev + json.choices[0].text;
});
} catch (error) {
console.log(error);
}
}
});
const data = resp.body;
if (!data) {
console.log("Error: No data received from API");
return;
}
const reader = resp.body.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
setLoading(false);
break;
}
const str = new TextDecoder().decode(value);
parser.feed(str);
}
} finally {
reader.releaseLock();
}
};

In the above code, we use the fetch API to send an HTTP request and obtain a readable stream in the response. We can use the getReader method to obtain a reader object and use it to process stream data, using the eventsource-parser package to parse data from server-sent events.

The content of the response will be displayed one by one according to Server-sent events (events sent by the server).

基于 ChatGPT API 的划词翻译浏览器脚本实现

#Text to speech

General translation Plug-ins all have voice playback functions, and we can use the Web Speech API. This API provides two speech synthesis interfaces: SpeechSynthesis and SpeechSynthesisUtterance

function speak(text) {
if ('speechSynthesis' in window) {
const utterance = new SpeechSynthesisUtterance(text);
utterance.voice = speechSynthesis.getVoices()[0];
utterance.pitch = 1;
utterance.rate = 1;
speechSynthesis.speak(utterance);
}
}

Then call this function directly and pass in the text that needs to be read aloud to realize speech playback

speak('Hello, world!');

Summary

This article introduces how to implement the basic functions of word translation, including using the interface provided by OpenAI for translation, adding buttons that trigger translation and mouse-up event monitoring events in the HTML page, using AJAX requests to obtain translation results from the interface, and It is displayed in a DIV element. It also introduces how to use webpack react antd to implement a modern plug-in and use the Web Speech API to implement the voice playback function.

The above is the detailed content of Implementation of word-marking translation browser script based on ChatGPT API. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
How to Build Your Personal AI Assistant with Huggingface SmolLMHow to Build Your Personal AI Assistant with Huggingface SmolLMApr 18, 2025 am 11:52 AM

Harness the Power of On-Device AI: Building a Personal Chatbot CLI In the recent past, the concept of a personal AI assistant seemed like science fiction. Imagine Alex, a tech enthusiast, dreaming of a smart, local AI companion—one that doesn't rely

AI For Mental Health Gets Attentively Analyzed Via Exciting New Initiative At Stanford UniversityAI For Mental Health Gets Attentively Analyzed Via Exciting New Initiative At Stanford UniversityApr 18, 2025 am 11:49 AM

Their inaugural launch of AI4MH took place on April 15, 2025, and luminary Dr. Tom Insel, M.D., famed psychiatrist and neuroscientist, served as the kick-off speaker. Dr. Insel is renowned for his outstanding work in mental health research and techno

The 2025 WNBA Draft Class Enters A League Growing And Fighting Online HarassmentThe 2025 WNBA Draft Class Enters A League Growing And Fighting Online HarassmentApr 18, 2025 am 11:44 AM

"We want to ensure that the WNBA remains a space where everyone, players, fans and corporate partners, feel safe, valued and empowered," Engelbert stated, addressing what has become one of women's sports' most damaging challenges. The anno

Comprehensive Guide to Python Built-in Data Structures - Analytics VidhyaComprehensive Guide to Python Built-in Data Structures - Analytics VidhyaApr 18, 2025 am 11:43 AM

Introduction Python excels as a programming language, particularly in data science and generative AI. Efficient data manipulation (storage, management, and access) is crucial when dealing with large datasets. We've previously covered numbers and st

First Impressions From OpenAI's New Models Compared To AlternativesFirst Impressions From OpenAI's New Models Compared To AlternativesApr 18, 2025 am 11:41 AM

Before diving in, an important caveat: AI performance is non-deterministic and highly use-case specific. In simpler terms, Your Mileage May Vary. Don't take this (or any other) article as the final word—instead, test these models on your own scenario

AI Portfolio | How to Build a Portfolio for an AI Career?AI Portfolio | How to Build a Portfolio for an AI Career?Apr 18, 2025 am 11:40 AM

Building a Standout AI/ML Portfolio: A Guide for Beginners and Professionals Creating a compelling portfolio is crucial for securing roles in artificial intelligence (AI) and machine learning (ML). This guide provides advice for building a portfolio

What Agentic AI Could Mean For Security OperationsWhat Agentic AI Could Mean For Security OperationsApr 18, 2025 am 11:36 AM

The result? Burnout, inefficiency, and a widening gap between detection and action. None of this should come as a shock to anyone who works in cybersecurity. The promise of agentic AI has emerged as a potential turning point, though. This new class

Google Versus OpenAI: The AI Fight For StudentsGoogle Versus OpenAI: The AI Fight For StudentsApr 18, 2025 am 11:31 AM

Immediate Impact versus Long-Term Partnership? Two weeks ago OpenAI stepped forward with a powerful short-term offer, granting U.S. and Canadian college students free access to ChatGPT Plus through the end of May 2025. This tool includes GPT‑4o, an a

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use