2

I'm trying to write a Chrome extension that takes the webpage text and send it to ChatGPT. Here's my JS code:

document.addEventListener('DOMContentLoaded', function () {
var getBattleCardButton = document.getElementById('get-battle-card-button');
getBattleCardButton.addEventListener('click', function () {
    // Get all the content on the page as a string
    var pageContent = document.body.innerText;

    // Truncate the content to a maximum length of 4096 tokens
    var truncatedContent = pageContent.substring(0, 4096);

    // Construct the prompt by concatenating the specific words with the page content
    var prompt = "Summarize this content into 3 sections, What? Why? and How?. Each section with 3 concise points. " + truncatedContent;

    // Send the page content to Chat GPT as a prompt
    fetch('https://api.openai.com/v1/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer MY_API_KEY'
        },
        body: JSON.stringify({
            'prompt': prompt,
            'model': 'text-davinci-003',
            'max_tokens': 512
        })
    })
        .then(response => response.json())
        .then(data => {
            // Open a new tab and insert the Chat GPT output into it
            var newTab = window.open();
            newTab.document.body.innerHTML = data.response;
        })
        .catch(error => {
            console.error('Error:', error);
        });
});

});

I'm getting the error "We could not parse the JSON body of your request." and the output is 'undefined'. What am I doing wrong?

PS: the HTML and CSS on the extension works just fine.

Rubén
  • 34,714
  • 9
  • 70
  • 166
Bob Bob
  • 154
  • 1
  • 11

0 Answers0