chatgpt.js is a powerful JavaScript library that allows for super easy interaction w/ the ChatGPT DOM.
- Importing the library
- Library methods
- Library APIs
Note To always import the latest version (not recommended in production!) replace the versioned jsDelivr URL with:
https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js/chatgpt.min.js
(async () => {
await import('https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.5.0/dist/chatgpt.min.js');
// Your code here...
})();
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.5.0/dist/chatgpt.min.js');
xhr.onload = function () {
if (xhr.status === 200) {
var chatgptJS = document.createElement('script');
chatgptJS.textContent = xhr.responseText;
document.head.append(chatgptJS);
yourCode(); // runs your code
}
};
xhr.send();
function yourCode() {
// Your code here...
}
Note To use a starter template: kudoai/chatgpt.js-greasemonkey-starter
...
// @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.5.0/dist/chatgpt.min.js
// ==/UserScript==
// Your code here...
Note To use a starter template: kudoai/chatgpt.js-chrome-starter
-
Save https://raw.githubusercontent.com/KudoAI/chatgpt.js/main/chatgpt.js to a subdirectory (
lib
in this example) -
Add ES6 export statement to end of
lib/chatgpt.js
...
export { chatgpt }
- In project's (V3)
manifest.json
, addlib/chatgpt.js
as a web accessible resource
"web_accessible_resources": [{
"matches": ["<all_urls>"],
"resources": ["lib/chatgpt.js"]
}],
- In scripts that need
chatgpt.js
(foreground/background alike), import it like so:
(async () => {
const { chatgpt } = await import(chrome.runtime.getURL('lib/chatgpt.js'));
// Your code here...
})();
Unless noted otherwise, methods are synchronous: they wait for the operation to finish, instead of returning immediately. If you need to know the result of calling asynchronous methods, use the returned promise or pass a callback function into the method.
Asks ChatGPT to detect the language of given text.
Parameters:
text
: A string being the text to detect the language of.
Example code:
(async () => {
const language = await chatgpt.detectLanguage('我是一個大男孩');
chatgpt.alert(language);
/* Alerts:
Chinese (Traditional) */
})();
Asks ChatGPT to execute the given code.
Parameters:
code
: A string being the code to execute.
Example code:
(async () => {
chatgpt.alert(await chatgpt.executeCode('return 6 + 5')); // logs '11'
})();
Returns a random IP address as a string.
Example code:
const randomIP = chatgpt.generateRandomIP();
chatgpt.alert(randomIP); // Example output: '161.192.110.125'
Example code:
var response;
response = chatgpt.get('reply', 'last');
// Equivalent of
response = chatgpt.getLastResponse();
Returns the user language as a string.
Example code:
const userLanguage = chatgpt.getUserLanguage();
chatgpt.alert(userLanguage); // Example output: 'en-US'
Returns a boolean value. true
if the website is fullscreen and false
otherwise.
Example code:
if (chatgpt.isFullScreen()) {
// Do something
}
Resolves a promise when ChatGPT has finished loading.
Parameters:
timeout
(optional): An integer specifying the number of milliseconds to wait before resolving with false
. If not provided, waits indefinitely until ChatGPT finishes loading.
Example code:
(async () => {
await chatgpt.isLoaded();
chatgpt.alert('ChatGPT has finished loading.');
})();
Prints all the library functions to the console.
Example code:
chatgpt.printAllFunctions();
Returns a random, cryptographically secure float number between 0 (inclusive) and 1 (exclusive).
Example code:
const randomNumber = chatgpt.randomFloat();
chatgpt.alert(randomNumber); // Example output: 0.9472113021060851
Cleans and renders given HTML code.
Parameters:
node
: A string representing the HTML to be rendered.
Example code:
document.body.append(
chatgpt.renderHTML('<div>Hello World!</div>');
);
Asks ChatGPT to analyze sentiment from a given text.
Parameters:
text
: A string being the text to be analyzed.
entity
(optional): A string being the entity to analyze sentiment towards.
Example code:
(async () => {
const text = 'Are you an #OSS supporter? Do you love JavaScript? Then why not contribute to the future of #AI app development? https://chatgpt.js.org (a #100Builders project) is seeking collabs for exactly this! @withBackdrop';
const sentiment = await chatgpt.sentiment(text, '100 Builders');
chatgpt.alert(sentiment);
/* Example output:
The sentiment of the text towards the entity "100 Builders" is strongly positive. The text encourages
individuals who support open-source software (OSS) and have an affinity for JavaScript to get involved with
the project. Phrases like "contribute to the future," "seeking collabs," and the inclusion of the hashtag
#100Builders project indicate a positive and enthusiastic tone, promoting engagement and collaboration
with the project. */
})();
Asks ChatGPT to suggest ideas.
Parameters:
ideaType
: A string being the type of idea to suggest.
details
(optional): A string being details to fine-tune the suggestion.
Example code:
(async () => {
const suggestions = await chatgpt.suggest('names', 'baby boy');
chatgpt.alert(suggestions);
/* Example output:
1. Liam
2. Noah
3. Ethan
4. Oliver
5. Jackson
6. Aiden
7. Lucas
8. Benjamin
9. Henry
10. Leo
11. Samuel
12. Caleb
13. Owen
14. Daniel
15. Elijah
16. Matthew
17. Alexander
18. James
19. Nathan
20. Gabriel */
})();
Asks ChatGPT to summarize given text.
Parameters:
text
: A string being the text to be summarized.
Example code:
(async () => {
const summary = await chatgpt.summarize('A very long text...');
chatgpt.alert(summary); // Example output: 'A very short text...'
})();
Asks ChatGPT to translate given text to a given language.
Parameters:
text
: A string being the text to translate.
outputLang
: A string representing the output language of the translation.
Example code:
(async () => {
const translation = await chatgpt.translate('Hello, how are you?', 'spanish');
chatgpt.alert(translation); // Alerts: 'Hola, ¿cómo estás?'
})();
Example code:
const randomID = chatgpt.uuidv4();
chatgpt.alert(randomID); // Example output: '239067d1-bcb8-4fd7-91eb-9ab94619b7b3'
Changes the website theme to dark mode.
Example code:
chatgpt.activateDarkMode();
Changes the website theme to light mode.
Example code:
chatgpt.activateLightMode();
Returns a boolean value. true
if the theme is dark mode, false
otherwise.
Example code:
chatgpt.alert(chatgpt.settings.scheme.isDark()); // logs `true` or `false`
Returns a boolean value. true
if the theme is light mode, false
otherwise.
Example code:
chatgpt.alert(chatgpt.settings.scheme.isDark()); // logs `true` or `false`
Toggles the theme between light and dark mode.
Example code:
chatgpt.toggleScheme();
Creates a static alert box which displays a message. Only a user interaction can close it. Returns the HTML id
property of the alert box as a string.
Parameters:
title
(optional): A string which is the title of the alert.
msg
(optional): A string which is the message to be displayed.
btns
(optional): An array of functions which will be rendered as clickable buttons.
checkbox
(optional): A function which will be rendered as a checkbox.
width
(optional): An integer representing the width of the alert box in px
.
Example code:
function doSomething() { /* Your code */ }
function doSomethingElse() { /* Your code */ }
function sayHello() { chatgpt.alert('Hello!'); }
const alertID = chatgpt.alert('Hello, world!', 'The sky is blue.', [doSomething, doSomethingElse], sayHello, 200);
chatgpt.alert(alertID); // Example output: '1693237957878'
Displays a temporary notification at a specified position in the website.
Parameters:
msg
: A string which is the message to be displayed.
position
(optional): A string specifying the position of the notification.
notifDuration
(optional): A float specifying the duration of the notification before it fades out.
shadow
(optional): A string specifying if the box-shadow
CSS property should be used.
Example code:
chatgpt.notify('Hello, world!', 'top left', 3, 'on');
Returns an account access token as a string.
(async () => {
const token = await chatgpt.getAccessToken();
chatgpt.alert(token); // Example output: 'abcdef[...]'
})();
Returns a given account detail as a string.
Parameters:
detail
: A string representing the account detail(s) that will be returned.
Can be the following: email
, id
, image
, name
, picture
. If a single detail is passed, it will be returned as a string, if multiple are passed instead, the function will return an object with the requested details. If no details are passed, the function will return an object with all the available details.
(async () => {
const accountName = await chatgpt.getAccountDetails('name');
chatgpt.alert(accountName); // Example output: 'chatgpt.js'
const accountData = await chatgpt.getAccountDetails('name', 'email');
chatgpt.alert(accountData);
/* Example output:
{
name: 'chatgpt.js',
email: 'showcase@chatgptjs.org'
}
*/
})();
Logs out the user from the website.
Example code:
chatgpt.logout();
Sends a given message to ChatGPT and returns the response as a string.
Example code:
(async () => {
const response = await chatgpt.askAndGetReply('Hello, ChatGPT');
chatgpt.alert(response); // Example output: 'Hello user, I'm ChatGPT!'
})();
Clears chat history.
Example code:
chatgpt.clearChats().then(() => chatgpt.alert('Chat history cleared!'));
Exports a given chat as a file.
Parameters:
chatToGet
(optional): A string representing the chat to get the data from.
Can be the following: active
, the current chat, latest
, the latest chat in the list, else the index
, title
or id
of the chat to get. Default is active
if in a chat, else latest
.
format
(optional): A string representing the format of the export file.
Can be the following: html
, md
, pdf
or text
. Defaults to html
.
Example code:
(async () => {
await chatgpt.exportChat('latest', 'html'); // Downloads a '.html' file
})();
Returns the requested chat data as a string (if single detail requested) or object of key-value pairs (if multiple details requested).
Parameters:
chatToGet
(optional): A string representing the chat to get the data from.
Can be the following: active
, the current chat, latest
, the latest chat in the list, else the index
, title
or id
of the chat to get. Default is active
if in a chat, else latest
.
detailsToGet
(optional): A string or array of strings representing the chat data to retrieve.
Can be the following: all
to get all details, id
, title
, create_time
, update_time
or msg
. To get a single detail, just use a string, to get multiple use an array of strings instead. Default is all
.
If msg
is the requested detail, the following parameters can be used:
sender
(optional): A string representing the chat member to get the message(s) from.
Can be the following: user
to get the user message(s), chatgpt
to get ChatGPT's response(s), all
/both
to get both of them. Default is all
.
msgToGet
(optional): A string/number representing the chat message to retrieve.
Can be the following: all
to get all the messages in the chat, latest
to get the latest message/response, or the index
of the message. Default is all
.
Note If any user messages were edited, they are added to the index as newly sent messages
Example code for all return types:
All details from specified chat
await chatgpt.getChatData();
// or
await chatgpt.getChatData('latest'); // can also be 'active', 'title of the chat' or 'id of the chat'
// or
await chatgpt.getChatData('latest', 'all');
Returns a JSON object
{
"create_time": "2023-07-19T13:24:05.618539+00:00",
"id": "e193a219-2311-4232-95f5-8e3a0e466652",
"title": "Lemons: Citrus Fruit Overview.",
"update_time": "2023-07-19T13:24:18+00:00"
}
Specific detail(s) from specified chat
await chatgpt.getChatData('latest', ['id', 'title']);
Returns a JSON object
{
"id": "e193a219-2311-4232-95f5-8e3a0e466652",
"title": "Lemons: Citrus Fruit Overview."
}
All messages from both participants in a specified chat
await chatgpt.getChatData('latest', 'msg');
// or
await chatgpt.getChatData('latest', 'msg', 'all'); // all/both
// or
await chatgpt.getChatData('latest', 'msg', 'all', 'all');
Returns an array of JSON objects
In case of a response being regenerated, the chatgpt
object key will be converted to an array containing all the responses.
[
{
"user": "what are lemons",
"chatgpt": "Lemons are a type of citrus fruit that belongs..."
},
{
"user": "be more specific",
"chatgpt": [
"Certainly! Here are some more specific...",
"Certainly! Here are some specific..." // regenerated responses!
]
}
]
All messages from a specific participant in a specified chat
await chatgpt.getChatData('latest', 'msg');
// or
await chatgpt.getChatData('latest', 'msg', 'chatgpt'); // user/chatgpt
// or
await chatgpt.getChatData('latest', 'msg', 'chatgpt', 'all');
Returns an array of strings/arrays
In case of a response being regenerated and the requested participant being chatgpt
, it'll be converted to an array containing all the responses.
[
"Lemons are a type of citrus fruit that belongs...",
[
"Certainly! Here are some more specific details...",
"Certainly! Here are some specific..."
]
]
One/latest message from both participants in a specified chat
await chatgpt.getChatData('latest', 'msg', 'all', 2); // can also be 'latest' message
Returns a JSON object
In case of a response being regenerated, the chatgpt
object key will be converted to an array containing all the responses.
{
"user": "be more specific",
"chatgpt": [
"Certainly! Here are some more specific...",
"Certainly! Here are some specific..."
]
}
One/latest message from a specific participant in a specified chat
await chatgpt.getChatData('latest', 'msg', 'chatgpt', 2);
Returns a string or an array of strings
In case of a response being regenerated, the chatgpt
object key will be converted to an array containing all the responses.
"Certainly! Here are some more specific..."
// or
[
"Certainly! Here are some more specific...",
"Certainly! Here are some specific..."
]
Returns the value of the chat input field as a string.
Example code:
const chatInput = chatgpt.getChatInput();
chatgpt.alert(chatInput); // Example output: 'Hello from chatgpt.js!'
Returns the last message sent by the user as a string.
(async () => {
const message = await chatgpt.getLastPrompt();
chatgpt.alert(message); // Example output: 'Hello from chatgpt.js!'
})();
Returns the last ChatGPT response as a string.
(async () => {
const response = await chatgpt.getLastResponse();
chatgpt.alert(response); // Example output: 'I am ChatGPT!'
})();
If it's a previously created chat, see chatgpt.getResponseFromDOM
If it's a new chat, see chatgpt.getResponseFromAPI
Returns the Nth response ChatGPT has written in a Nth chat as a string.
Parameters:
chatToGet
(optional): A number representing the index of the chat to get the response from. Defaults to latest
.
responseToGet
(optional): A number representing the index of the response to get. Defaults to latest
.
Example code:
(async () => {
const response = chatgpt.getResponseFromAPI();
chatgpt.alert(response); // Example output: 'Hello from ChatGPT!'
})();
Returns the Nth response ChatGPT has written as a string.
Parameters:
pos
: A string or integer representing the position of the wanted response.
Example code:
var fifthResp;
fifthResp = chatgpt.getResponseFromDOM(5); // Returns the 5th response
fifthResp = chatgpt.getResponseFromDOM('fifth'); // Also returns the 5th response
fifthResp = chatgpt.getResponseFromDOM('five'); // Returns the 5th response too
chatgpt.alert(fifthResp); // Example output: 'Hello from ChatGPT!'
Resolves a promise when ChatGPT has finished generating a response.
Parameters:
timeout
(optional): An integer specifying the number of milliseconds to wait before resolving with false
. If not provided, waits indefinitely until response generation finishes.
Example code:
(async () => {
await chatgpt.code.isIdle();
chatgpt.alert('ChatGPT is idle');
})();
Regenerates ChatGPT's response.
Example code:
chatgpt.regenerate();
Re-sends the last user message.
(async () => {
await chatgpt.resend();
})();
Scrolls to the bottom of the chat.
Example code:
chatgpt.scrollToBottom();
Sends a message into the chat.
Parameters:
msg
: A string representing the message to send.
method
(optional): A string representing the method to send the message with, can only be click
. Usually needed for mobile devices compatibility.
Example code:
// Clicks the send button instead of triggering the 'Enter' key press.
chatgpt.send('Hello, world!', 'click');
Creates a new chat and sends a message.
Parameters:
msg
: A string representing the message to send.
Example code:
chatgpt.sendInNewChat('Hello, world!');
Makes the selected chat available to others. Returns the URL of the chat as a string.
Parameters:
chatToGet
(optional): A number or string representing the index
, title
or id
of the chat to share.
method
(optional): A string representing the method to share the chat with. Defaults to clipboard
.
Can be the following: copy
or clipboard
to copy the chat URL to clipboard, alert
, notify
or notification
to create an alert message with the details about the shared chat in the website.
(async () => {
await chatgpt.shareChat(1, 'copy'); // copy/clipboard
})();
Text To Speech (TTS) conversion of a given message.
Parameters:
msg
: A string representing the message to TTS.
options
(optional): An object containing the options for the vocal synthesizer.
Available options:
voice
: A number representing the index of voices available on the user device.pitch
: A float representing the pitch of the speech. From0
to2
.speed
: A float representing the speed of the speech. From0.1
to10
.
Example code:
(async () => {
chatgpt.speak(await chatgpt.getLastResponse(), { voice: 1, pitch: 2, speed: 3 });
})();
Creates a new chat.
Example code:
chatgpt.startNewChat();
Stops the generation of ChatGPT's response.
Example code:
chatgpt.stop();
Focuses the chatbar.
Example code:
chatgpt.focusChatbar();
Returns the chat input as an HTML element.
Example code:
const chatbox = chatgpt.getChatBox();
chatgpt.alert(chatbox.value); // Example output: 'Hello from chatgpt.js!'
Returns the 'Continue generating' button as an HTML element.
Example code:
const continueBtn = chatgpt.getContinueButton();
continueBtn.click();
Returns the footer div as an HTML element.
Example code:
const footerDiv = chatgpt.getFooterDiv();
footerDiv.style.padding = '15px'; // make the footer taller
Returns the header div as an HTML element.
Example code:
const headerDiv = chatgpt.getHeaderDiv();
headerDiv.style.display = none; // hide the header
Returns the sidebar button (w/ icon) that creates a new chat as an HTML element.
Example code:
const newChatBtn = chatgpt.getNewChatButton();
newChatBtn.style.display = 'none'; // hide New Chat button
Returns the sidebar link (w/ label) that creates a new chat as an HTML element.
Example code:
const newChatLink = chatgpt.getNewChatLink();
newChatLink.style.display = 'none'; // hide New Chat link
Returns the button which regenerates ChatGPT's response as an HTML element.
Example code:
const regenBtn = chatgpt.getRegenerateButton();
regenBtn.click();
Returns the button which scrolls to bottom as an HTML element.
Example code:
const scrollToBottomBtn = chatgpt.getScrollToBottomButton();
scrollToBottomBtn.click();
Returns the button which sends the message as an HTML element.
Example code:
const sendBtn = chatgpt.getSendButton();
sendBtn.click();
Returns the button which stops the generation of ChatGPT's response as an HTML element.
Example code:
const stopBtn = chatgpt.getStopGeneratingButton();
stopBtn.click();
Hides the footer div.
Example code:
chatgpt.hideFooter()
Hides the header div.
Example code:
chatgpt.hideHeader()
Shows the footer div if hidden.
Example code:
chatgpt.showFooter()
Shows the header div if hidden.
Example code:
chatgpt.showHeader()
API related to keeping the user's session alive and fresh.
Activates the auto-refresh functionality.
Parameters:
interval
(optional): A number representing the interval in seconds between sessions refreshes. Defaults to 30
.
Example code:
chatgpt.autoRefresh.activate();
Deactivates the auto-refresh functionality.
Example code:
chatgpt.autoRefresh.deactivate();
Returns the current timestamp as a string (12-hour format).
Example code:
const timeStamp = chatgpt.autoRefresh.nowTimeStamp();
chatgpt.alert(timeStamp); // Example output: '1:56:25 PM'
Returns a boolean value. true
if system/browser scheme preference is set to light, false
otherwise.
Example code:
chatgpt.alert(chatgpt.browser.isLightMode()); // logs `true` or `false`
Returns a boolean value. true
if system/browser scheme preference is set to dark, false
otherwise.
Example code:
chatgpt.alert(chatgpt.browser.isDarkMode()); // logs `true` or `false`
Returns a boolean value. true
if the browser is Chromium and false
otherwise.
Example code:
if (chatgpt.browser.isChromium()) {
// Do something
}
Returns a boolean value. true
if the browser is Chrome and false
otherwise.
Example code:
if (chatgpt.browser.isChrome()) {
// Do something
}
Returns a boolean value. true
if the browser is Edge and false
otherwise.
Example code:
if (chatgpt.browser.isEdge()) {
// Do something
}
Returns a boolean value. true
if the browser is Brave and false
otherwise.
Example code:
if (chatgpt.browser.isBrave()) {
// Do something
}
Returns a boolean value. true
if the browser is Firefox and false
otherwise.
Example code:
if (chatgpt.browser.isFirefox()) {
// Do something
}
Returns a boolean value. true
if the browser is fullscreen and false
otherwise.
Example code:
if (chatgpt.browser.isFullScreen()) {
// Do something
}
Returns a boolean value. true
if the browser is mobile and false
otherwise.
Example code:
if (chatgpt.browser.isMobile()) {
// Do something
}
Asks ChatGPT to minify the given code.
Parameters:
code
: A string being the code to be minified.
Example code:
(async () => {
const minifiedCode = await chatgpt.code.minify(`
function autosizeBox() {
const newLength = replyBox.value.length
if (newLength < prevLength) { // if deleting txt
replyBox.style.height = 'auto' // ...auto-fit height
if (parseInt(getComputedStyle(replyBox).height) < 55) { // if down to one line
replyBox.style.height = '2.15rem' } // ...reset to original height
}
replyBox.style.height = replyBox.scrollHeight + 'px'
prevLength = newLength
}`);
chatgpt.alert(minifiedCode);
/* Alerts:
'function autosizeBox(){const n=replyBox.value.length;if(n<prevLength){replyBox.style.height='auto';if(parseInt(getComputedStyle(replyBox).height)<55){replyBox.style.height='2.15rem'}}replyBox.style.height=replyBox.scrollHeight+'px';prevLength=n}' */
})();
Asks ChatGPT to execute the given code.
Parameters:
code
: A string being the code to execute.
Example code:
(async () => {
chatgpt.alert(await chatgpt.code.execute('return 6 + 5')); // logs '11'
})();
Extracts pure code from response.
Parameters:
msg
: A string being the response to extract code from.
Example code:
(async () => {
chatgpt.send('What is a short script to delete files?');
await chatgpt.isIdle();
const response = await chatgpt.getChatData('active', 'msg', 'chatgpt', 'latest'),
scriptCode = chatgpt.code.extract(response);
chatgpt.alert(scriptCode);
/* Alerts:
const fs = require('fs');
// Specify the path of the file(s) you want to delete
const filePath = 'path/to/your/file.txt';
// Delete the file
fs.unlink(filePath, (err) => {
if (err) {
console.error('Error deleting file:', err);
} else {
chatgpt.alert('File deleted successfully');
}
}); */
})();
Resolves a promise when code has finished generating.
Parameters:
timeout
(optional): An integer specifying the number of milliseconds to wait before resolving with false
. If not provided, waits indefinitely until code generation finishes.
Example code:
(async () => {
chatgpt.send('Type me a short code block');
await chatgpt.code.isIdle();
chatgpt.alert('Code finished generating'); // non-code may still be generating
})();
Asks ChatGPT to obfuscate the given code.
Parameters:
code
: A string being the code to obfuscate.
Example code:
(async () => {
const code = `window[elem].addEventListener('mouseover', toggleTooltip)`
const obfuscatedCode = await chatgpt.code.obfuscate(code);
chatgpt.alert(obfuscatedCode);
/* Alerts:
'(window[elem])[btoa('YWxlcnRWaWV3')](btoa('bW91c2VyYm94ZXJOYW1l'), btoa('dG9nZ2VkT3V0d2FsbA==')); */
})();
Asks ChatGPT to refactor the given code.
Parameters:
code
: A string being the code to refactor.
objective
(optional): A string representing the objective of the refactoring. Defaults to brevity
.
Example code:
(async () => {
const code = `
if (6 > 5) {
return true;
} else {
return false;
}`;
const refactoredCode = await chatgpt.code.refactor(code, 'brevity');
chatgpt.alert(refactoredCode);
/* Alerts:
return 6 > 5; */
})();
Asks ChatGPT to review given code.
Parameters:
code
: A string being the code to review.
Example code:
(async () => {
chatgpt.alert(await chatgpt.code.review('btoa("Hello World")'));
/* Example output:
The code appears to be correct. It uses the `btoa` function to encode the string "Hello World" in base64. */
})();
Asks ChatGPT to unminify the given code.
Parameters:
code
: A string being the code to unminify.
Example code:
(async () => {
const code = `function autosizeBox(){const n=replyBox.value.length;if(n<prevLength){replyBox.style.height='auto';if(parseInt(getComputedStyle(replyBox).height)<55){replyBox.style.height='2.15rem'}}replyBox.style.height=replyBox.scrollHeight+'px';prevLength=n}`;
const minifiedCode = await chatgpt.code.unminify(code);
chatgpt.alert(minifiedCode);
/* Alerts:
function autosizeBox() {
const newLength = replyBox.value.length
if (newLength < prevLength) { // if deleting txt
replyBox.style.height = 'auto' // ...auto-fit height
if (parseInt(getComputedStyle(replyBox).height) < 55) { // if down to one line
replyBox.style.height = '2.15rem' } // ...reset to original height
}
replyBox.style.height = replyBox.scrollHeight + 'px'
prevLength = newLength
}` */
})();
Asks ChatGPT to write code given a prompt.
Parameters:
prompt
: A string describing the code to generate.
outputLang
: A string representing the code language to generate the prompt with.
Example code:
(async () => {
const code = await chatgpt.code.write('Repeat a task every 10 seconds', 'javascript');
chatgpt.alert(code);
/* Alerts:
setInterval(function() {
// Your task code here
}, 10000); */
})();
API related to the footer.
Returns the footer div as an HTML element.
Example code:
const footerDiv = chatgpt.footer.get();
footerDiv.style.padding = '15px'; // make the footer taller
Hides the footer div.
Example code:
chatgpt.footer.hide()
Shows the footer div if hidden.
Example code:
chatgpt.footer.show()
API related to the header.
Returns the header div as an HTML element.
Example code:
const headerDiv = chatgpt.header.get();
headerDiv.style.display = none; // hide the header
Hides the header div.
Example code:
chatgpt.header.hide()
Shows the header div if hidden.
Example code:
chatgpt.header.show()
API related to the chat history.
Resolves a promise when chat history has finished loading.
Parameters:
timeout
(optional): An integer specifying the number of milliseconds to wait before resolving with false
. If not provided, waits indefinitely until chat history finishes loading.
Example code:
(async () => {
await chatgpt.history.isLoaded();
chatgpt.alert('ChatGPT history has finished loading.');
})();
Adds a custom instruction for either the user or ChatGPT.
Parameters:
instruction
: A string being the instruction to be added.
target
: A string representing the target of the instruction. Can be either user
or chatgpt
.
Example code:
(async () => {
await chatgpt.instructions.add('Detailed and well-explained answers', 'chatgpt');
})();
Clears the custom instructions of either the user or ChatGPT.
Parameters:
target
: A string representing the target of the instruction. Can be either user
or chatgpt
.
Example code:
(async () => {
await chatgpt.instructions.clear('user');
})();
Turns off custom instructions.
Example code:
(async () => {
await chatgpt.instructions.turnOff();
})();
Turns on custom instructions.
Example code:
(async () => {
await chatgpt.instructions.turnOn();
})();
Toggles on/off custom instructions.
Example code:
(async () => {
await chatgpt.instructions.toggle();
})();
The small menu that shows up when clicking on the account button.
Opens the menu.
Example code:
chatgpt.menu.open();
Closes the menu.
Example code:
chatgpt.menu.close();
API related to ChatGPT's responses.
Continues the generation of ChatGPT's cut-off response.
Example code:
chatgpt.response.continue();
If it's a previously created chat, see chatgpt.getResponseFromDOM
If it's a new chat, see chatgpt.getResponseFromAPI
See chatgpt.getResponseFromAPI
See chatgpt.getResponseFromDOM
See chatgpt.stop
API for interfacing with ChatGPT user settings.
Returns a boolean value. true
if the theme is dark mode, false
otherwise.
Example code:
chatgpt.alert(chatgpt.settings.scheme.isDark()); // logs `true` or `false`
Returns a boolean value. true
if the theme is light mode, false
otherwise.
Example code:
chatgpt.alert(chatgpt.settings.scheme.isLight()); // logs `true` or `false`
Sets the theme to light
, dark
or system
.
Paremeters:
value
: A string being the value to set the theme to.
Example code:
chatgpt.settings.scheme.set('dark');
Toggles the theme between light and dark mode.
Example code:
chatgpt.settings.scheme.toggle();
API related to the sidebar's behavior.
Appends a new element to the sidebar. Returns the id
property of the element.
Parameters:
element
: A string being the name of the element to append.
Currently supported elements are button
and dropdown
.
attrs
: An object which contains the attributes of the element to append.
Attributes for button
label
: A string being the label (displayed text) of the button. Defaults to chatgpt.js button
.
icon
: A string being either a url to an image or a base64 encoded string of the image data. Defaults to this icon.
onclick
: A function which is called when the button is clicked. Defaults to function() {}
.
Attributes for dropdown
items
: An array of objects where the text
key is the displayed text of the option, and the value
key is the value of the option.
Example item object:
{
text: 'The text to display in the option',
value: 'The value of the option'
}
Example code:
const buttonId = chatgpt.sidebar.append('button', {
label: 'I am a button!',
icon: 'https://chat.openai.com/favicon-32x32.png',
onclick: function() {
chatgpt.alert('Clicked!');
}
});
chatgpt.alert(buttonId); // Example output: 1693295258727
const dropdownId = chatgpt.sidebar.append('dropdown', {
items: [
{ text: 'Hello world', value: 'helloworld' },
{ text: 'Hello there', value: 'hellothere' }
]
});
chatgpt.alert(dropdownId); // Example output: 1693294795240
Returns a boolean value. true
if the sidebar exists , false
otherwise (e.g. logged out UI).
Example code:
if (!chatgpt.sidebar.exists())
chatgpt.alert('Sidebar is missing!')
Returns a boolean value. true
if the sidebar is open, false
otherwise.
Example code:
if (chatgpt.sidebar.isOn()) {
// Do something
}
Returns a boolean value. true
if the sidebar is closed, false
otherwise.
Example code:
if (chatgpt.sidebar.isOff()) {
// Do something
}
Hides the sidebar.
Example code:
chatgpt.sidebar.hide();
Shows the sidebar.
Example code:
chatgpt.sidebar.show();
Toggles the visibility of the sidebar.
Example code:
chatgpt.sidebar.toggle();
Resolves a promise when the ChatGPT sidebar has finished loading.
Parameters:
timeout
(optional): An integer specifying the number of milliseconds to wait before resolving with false
. If not provided, waits 5s or until New Chat link appears (since it is not always present).
Example code:
(async () => {
await chatgpt.sidebar.isLoaded();
chatgpt.alert('ChatGPT sidebar has finished loading.');
})();